Python recursive solution for Basic Calculator


  • 0
    S

    Use calculateBracket to calculate an expression within a bracket, and return the value from this expression within bracket, also return the position after the ending bracket.

    Recursively call calculateBracket() whenever we see a "(".
    Return whenever we meet a ")", this way we always match each "(" and its ending ")"

    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        def calculateBracket(expression, leftStartIndex):  
            pos = leftStartIndex
            res = 0 
            sign = "+"
            while pos < len(expression) and expression[pos] != ")":
                tempRes = 0 
                if expression[pos] == "(":
                    pos, tempRes = calculateBracket(expression, pos+1)
                else:
                    if expression[pos].isdigit():
                        while pos<len(expression) and expression[pos].isdigit():
                            tempRes = tempRes*10 + int(expression[pos])
                            pos += 1
                    else:
                        if expression[pos] == "+" or expression[pos] == "-":
                            sign = expression[pos]
                        pos += 1
                if sign == "+":
                    res += tempRes
                elif sign == "-":
                    res -= tempRes
    
            return pos+1, res
    
        pos, result  = calculateBracket(s, 0)
        return result

Log in to reply
 

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