Python Solution


  • 0
    Y
        def solveEquation(self, equation):
            """
            :type equation: str
            :rtype: str
            """
            def cal(s):
                start=0
                co=0
                val=0
                s=s+"+"
                last=1
                if s[0]=="-":
                    last=-1
                    start=1
                for i in xrange(1,len(s)):
                    if s[i]=="+" or s[i]=="-":
                        tmp=s[start:i]
                        if "x" in tmp:
                            if len(tmp)>1:
                                co+=int(tmp[:len(tmp)-1])*last
                            else:
                                co+=1*last
                        else :
                            val+=int(tmp)*last
                        last=1 if s[i]=="+" else -1
                        start=i+1
                return (co,val)
    
    
            s=equation.split("=")
            left,right=cal(s[0]),cal(s[1])
            if left[0]==right[0]:
                if left[1]==right[1]:
                    res= "Infinite solutions"
                else:
                    res= "No solution"
            else:
                res="x="+str((right[1]-left[1])/(left[0]-right[0]))
                
            return res
    

Log in to reply
 

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