O(n) time, o(1) space, python, 260ms


  • 5
    I

    basic idea:

    only need 2 variable (a,b) to save the data.

    if operator is '*' or '/', use b to calculate , then save it to b.

    if operator is '+' or '-', then a = a +/- b b = new_number

    def calculate(self, s):
        s += '#'
        num = 0
        a = b = None
        preop = op = None
        for c in s:
            if c in ('+','-','*','/','#'):
                if op is None:
                    a = num
                elif op in ('+','-'):
                    if preop is None:
                        b = num
                    else:
                        a = a + b if preop == '+' else a - b
                        b = num
                    preop = op
                else:
                    if preop is None:
                        a = a * num if op == '*' else a / num
                    else:
                        b = b * num if op == '*' else b / num
                op = c
                num = 0
            elif c != ' ':
                num = num * 10 + int(c)
        if preop is None:
            return a
        return a + b if preop == '+' else a - b

Log in to reply
 

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