Python Easy Stack Solution


  • 0
    D
    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            eles = [x for x in s if x != ' ']
            ops = {'+': lambda x,y: x+y, '-':lambda x,y: x-y, '*':lambda x,y: x*y, '/':lambda x,y: x/y}
            stack = []
            i = 0
            while i < len(s):
                if s[i] in ops: 
                    stack.append(s[i])
                    i += 1
                else:
                    j = i+1
                    while j < len(s) and s[j] not in ops: j += 1
                    if not stack or stack[-1] == '+' or stack[-1] == '-': stack.append(int(s[i:j]))
                    else:
                        op = stack.pop()
                        last_ele = stack.pop()
                        ans = ops[op](last_ele, int(s[i:j]))
                        stack.append(ans)
                    i = j
            stack.reverse()
            while len(stack) > 1:
                curr = stack.pop()
                op = stack.pop()
                last = stack.pop()
                ans = ops[op](curr, last)
                stack.append(ans)
            return stack[0]

Log in to reply
 

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