Given a string
s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as
eval().Example 1:
Input: s = “1 + 1”
Output: 2
Example 2:
Input: s = “ 2-1 + 2 “
Output: 3
Example 3:
Input: s = “(1+(4+5+2)-3)+(6+8)”
Output: 23
Constraints:
`1 <= s.length <= 3 105
*sconsists of digits,‘+’,‘-‘,‘(‘,‘)’, and‘ ‘.
*srepresents a valid expression.
*‘+’is **not** used as a unary operation (i.e.,“+1”and“+(2 + 3)”is invalid).
*‘-‘could be used as a unary operation (i.e.,“-1”and“-(2 + 3)”` is valid).There will be no two consecutive operators in the input. Every number and running calculation will fit in a signed 32-bit integer.
题目大意:
实现字符串加减,但有括号。
算法思路:
括号题优先考虑用Stack。这里Stack不能只存数,因为括号前可以是正负,所以将这个信息以+1或-1也压入栈(栈不能混合字符和数字)
所以用一个stack,num是一个数,res是括号内的累积结果。num在处理完每一个数都要重设,res和sign在处理完每个括号都要重设。
运用模板,代码中含五种情况:空格,运算符,数字,左右括号。左括号将res和sign入栈,右括号将res和sign出栈,计算结果存在res
LeetCode 224 Basic Calculator 括号加减法, 同一层括号内求和遇括号入栈
LeetCode 227 Basic Calculator II 加减乘除, 和的每一项入栈,方便出栈计乘除
LeetCode 772 Basic Calculator III 加减乘除括号, L227的递归版
注意事项:
- 括号前可以是正负,所以将这个信息以+1或-1也压入栈
- 左括号无论前面是正负都要入栈
- num在处理完每一个数都要重设,res和sign在处理完每个括号都要重设
Python代码:
1 | # 1-(2+3)+(4+5) |
算法分析:
时间复杂度为O(n),空间复杂度O(n)


