Share my python solution


  • 0
    A
    class Solution(object):
        def solveEquation(self, equation):
            """
            :type equation: str
            :rtype: str
            """
            left, right = equation.split('=')
            
            def process(s):
                a, b = 0, 0
                if s[0] != '-':
                    s = '+' + s
                s = s + '+'
                prev_pos = 1 
                prev_sign = -1 if s[0] == '-' else 1
                for i, e in enumerate(s):
                    if e in ['-', '+']:
                        if i == 0:
                            continue
                        term = s[prev_pos:i]
                        if 'x' in term:
                            a += int(term[:-1]) * prev_sign if term[:-1] else prev_sign
                        else:
                            b += int(term) * prev_sign
                            
                        prev_pos = i+1
                        prev_sign = -1 if e=='-' else 1
                return a, b
            
            a, b = process(left)
            c, d = process(right)
            
            if (a == c):
                return "No solution" if b != d else "Infinite solutions"
            return "x=" + str(int((d-b)/(a-c)))
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.