【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))
        

 

posted @ 2018-09-17 17:48  seyjs  阅读(267)  评论(0编辑  收藏  举报