My simply O(1) space Python solution


  • 1
    Y
    class Solution(object):
    def calculate(self, s):
        s= s + '+'
        temp, num, op, res = 1, 0, '*', 0
        for c in s:
            if c ==' ':
                continue
            if c in '+-*/':
                if op == '*':
                    temp *= num
                else:
                    temp = abs(temp)/num if temp >= 0 else -(abs(temp)/num)
                num = 0
                if c in '+-':
                    res += temp
                    temp = 1 if c =='+' else -1
                    op = '*'
                else:
                    op = c
            else:
                num = 10*num + int(c)
        return res

Log in to reply
 

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