My python solution


  • 0
    Q
    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            from collections import deque
            plus = lambda x, y: x + y
            minus = lambda x, y: x - y
            s1 = deque([0])
            s2 = deque([plus])
            i = 0
            while i < len(s):
                if s[i] == ' ':
                    pass
                elif s[i] in ['+', '-']:
                    s2.append(plus if s[i] == '+' else minus)
                elif s[i] == '(':
                    s1 += '(',
                    s1 += 0,
                    s2 += plus,
                elif s[i] == ')':
                    secondvalue = s1.pop()
                    s1.pop() # remove opening parenthese
                    if s2:
                        firstvalue = s1.pop()
                        s1.append(s2.pop()(firstvalue, secondvalue))
                else:
                    start = i
                    while i < len(s) and ord('0') <= ord(s[i]) <= ord('9'):
                        i += 1
                    secondvalue = int(s[start:i])
                    if s2:
                        firstvalue = s1.pop()
                        s1.append(s2.pop()(firstvalue, secondvalue))
                    i -= 1
                i += 1
            return s1.pop()
    

Log in to reply
 

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