intuitive recursive python solution that needs no explanation


  • 0
    S
    def calculate(self, s):
    	formula = list(s)
    	formula.append(')')
    	return self.helper(formula, 0)[0]
    
    def helper(self, formula, i):
    	summ = 0
    	sign = 1
    	while formula[i] != ')':
    		if formula[i].isdigit():
    			start = i
    			while formula[i].isdigit():
    				i += 1
    			summ += int("".join(formula[start: i])) * sign
    		elif formula[i] == '(':
    			temp, i = self.helper(formula, i + 1)
    			summ += temp * sign
    		elif formula[i] == '-':
    			sign = -1
    			i += 1
    		elif formula[i] == '+':
    			sign = 1
    			i += 1
    		else:
    			i += 1
    	return summ, i + 1
    

Log in to reply
 

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