Leetcode 224 Solution

This article provides solution to leetcode question 224 (basic-calculator)

https://leetcode.com/problems/basic-calculator

Solution

class Solution:
    def calculate(self, s: str) -> int:
        def get_next_token(s, i):
            while i < len(s) and s[i] == ' ':
                i += 1

            if i == len(s):
                return None, i

            if s[i] in ['+', '-', '(', ')']:
                return s[i], i + 1

            j = i
            while j < len(s):
                if not s[j].isnumeric():
                    break
                j += 1
            return int(s[i:j]), j

        i = 0
        def evaluate(s):
            nonlocal i
            if i == len(s):
                return 0

            nums = []
            last_sign = '+'

            while i < len(s):
                token, i = get_next_token(s, i)

                if token == '+':
                    last_sign = '+'
                elif token == '-':
                    last_sign = '-'
                elif isinstance(token, int):
                    nums.append(token if last_sign == '+' else -token)
                elif token == '(':
                    child_val = evaluate(s)
                    nums.append(child_val if last_sign == '+' else -child_val)
                elif token == ')':
                    break
                elif token is None:
                    break
                else:
                    raise Exception("Unexpected token '{}'".format(token))

            return sum(nums)

        return evaluate(s)