[LeetCode] 224. Basic Calculator_Hard tag: stack

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.

The subject and because there is no * /, so there is no priority, it is still a good deal relative, but there are (), but there are similar 3 - (2--6), such a situation there is no parentheses and brackets is two results so we need to stack.

We sign to indicate the current symbol, default is 1, ans to represent the current numerical results, temp to represent the current digit, each digit to the end of the initialization sign and temp, if you see '(' the ans and sign append stack into the inside, the cycle continues calculating ANS, the event ''), it ans * = stack.pop (), ans + = stack.pop (), and the cycle continues. Finally, return 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

 

Guess you like

Origin www.cnblogs.com/Johnsonxiong/p/11281087.html