代码改变世界

[LeetCode] 224. Basic Calculator_Hard tag: stack

2019-08-01 10:46  Johnson_强生仔仔  阅读(202)  评论(0编辑  收藏  举报

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

Example 1:

Input: "1 + 1"
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

这个题目因为没有* 和/,所以没有优先级,还相对于较为好处理,只不过有(),而有类似于3 - (2 - 6),这样的情况有括号和没括号就是两种结果,所以要用stack。

我们用sign来表示当前的符号,default为1, ans 来表示目前的数值结果,temp来表示目前的digit,每次digit结束要初始化sign和temp,如果看到'(', 将ans和sign append进入stack里面,继续循环计算ans,一旦遇到')', 就ans *= stack.pop(), ans += stack.pop(), 然后继续循环。最后返回ans。

Code

class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack, digits, n, ans, sign, temp, i = [], "0123456789", len(s), 0, 1, "", 0
        while i < n:
            if s[i] == '-':
                sign = -1
            elif s[i] == '+':
                sign = 1
            elif s[i] in digits:
                while i < n and s[i] in digits:
                    temp += s[i]
                    i += 1
                ans += sign * int(temp)
                sign, temp = 1, ""
                i -= 1
            elif s[i] == '(':
                stack.append(ans)
                stack.append(sign)
                sign, ans = 1, 0
            elif s[i] == ')':
                ans *= stack.pop()
                ans += stack.pop()
            i += 1       
        return ans