zoukankan      html  css  js  c++  java
  • 【leetcode】640. Solve the Equation

    题目如下:

    解题思路:本题的思路就是解析字符串,然后是小学时候学的解方程的思想,以"2x+3x-6x+1=x+2",先把左右两边的x项和非x项进行合并,得到"-x+1=x+2",接下来就是移项,把x项移到左边,常数项移到右边,得到"2x=-1",最后的解就是x=-1/2。对于任意一个表达式ax+b = cx+d来说,最终都能得到解x=(d-b)/(a-c),这里要对(a-c)是否为0做判断,同时根据(d-b)是否为0等到Infinite solutions,No solution,常规解三种结果。

    代码如下:

    class Solution(object):
        def parse(self,expression):
            x,v = 0,0
            if expression[0] == '-':
                expression = '0' + expression
            item = ''
            operators = ['+', '-']
            operator = ''
            for i in (expression + '#'):
                if i in operators or i == '#':
                    if item == 'x':
                        item = '1x'
                    if operator == '':
                        operator = i
                        if item[-1] == 'x':
                            x = int(item[:-1])
                        else:
                            v = int(item)
                        item = ''
                    else:
                        if operator == '+' and item[-1] == 'x':
                            x += int(item[:-1])
                        elif operator == '-' and item[-1] == 'x':
                            x -= int(item[:-1])
                        elif operator == '+' and item[-1] != 'x':
                            v += int(item)
                        else:
                            v -= int(item)
                        item = ''
                        operator = i
                else:
                    item += i
            return x,v
        def solveEquation(self, equation):
            """
            :type equation: str
            :rtype: str
            """
            left,right = equation.split('=')
            lx,lv = self.parse(left)
            rx,rv = self.parse(right)
    
            if lx - rx == 0 and rv - lv == 0:
                return "Infinite solutions"
            elif lx - rx == 0 and rv - lv != 0:
                return "No solution"
            else:
                return "x=" + str((rv - lv)/(lx - rx))
            
  • 相关阅读:
    OkHttp的基本使用方法
    C#中Dictionary小记
    SQL Server表的数据量大小查询
    基于.NET平台常用的框架整理
    JQuery中ajax的相关方法总结
    JQuery中的工具函数总结
    Asp.net MVC 中Controller返回值类型ActionResult
    Plupload文件上传组件使用API
    HTTP 方法:GET 对比 POST
    C#使用简单邮件传输协议(SMTP)发送邮件
  • 原文地址:https://www.cnblogs.com/seyjs/p/9660467.html
Copyright © 2011-2022 走看看