Leetcode: Basic Calculator

来源:互联网 发布:floyd算法负权 编辑:程序博客网 时间:2024/06/08 04:49

Question

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 .

You may assume that the given expression is always valid.

Some examples:
“1 + 1” = 2
” 2-1 + 2 ” = 3
“(1+(4+5+2)-3)+(6+8)” = 23
Note: Do not use the eval built-in library function.

Hide Tags Stack Math
Hide Similar Problems (M) Evaluate Reverse Polish Notation (M) Basic Calculator II (M) Different Ways to Add Parentheses


Solution

Get idea from here, here2

class Solution(object):    def calculate(self, s):        """        :type s: str        :rtype: int        """        if s=='':            return 0        res, num, sign = 0, 0 , 1        stack = []        for elem in s:            if elem.isdigit():                num = num*10 + ord(elem) - ord('0')            else:                if elem == '+':                    res += num*sign                    sign = 1                elif elem == '-':                    res += num*sign                    sign = -1                elif elem=='(':                    stack.append(res)                    stack.append(sign)                    res, sign = 0, 1     # calculate a new string, like '0+expression'                elif elem==')':                    res += num*sign                    res *= stack.pop(-1)                    res += stack.pop(-1)                    sign = 1                else:                    continue                num = 0        res += num*sign        return res
0 0