题目描述
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-negativeintegers and empty spaces ``.
Example 1:
1 | Input: "1 + 1" |
Example 2:
1 | Input: " 2-1 + 2 " |
Example 3:
1 | Input: "(1+(4+5+2)-3)+(6+8)" |
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
这题需要实现一个简单的计算器,比较难的点在于如何处理括号。在对字符串进行处理后,根据’+’, ‘-‘, ‘(‘, ‘)’作为分隔符,得到每一个数字和他们对应的运算符号,存在一个list里。
每次遇到’(‘的时候,就需要进行一次递归,在遇到’)’的时候,从该层递归返回结果。
代码实现
1 | class Solution: |