题目:
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
思路:
我原来的解法是采用栈分别存储操作符和操作数,遇到左括弧则入栈,遇到运算符则计算,遇到右括弧则左右括弧同时出栈。代码思路直观,但是非常冗长。
在网上参考了一个利用递归思想的实现,觉得非常精妙。它的实现采用的是深度优先搜索,如果碰到左括弧就递归到下一层,处理括弧里面的计算,如果碰到右括弧就返回当前一层的值。
代码:
class Solution {
public:
int calculate(string s) {
s = "(" + s + ")";
int k = 1;
return DFS(s, k);
}
private:
int DFS(string &s, int &i) {
int ret = 0, c = 1, num = 0;
while (i < s.size()) {
if (isdigit(s[i])) {
num = num * 10 + (s[i] - '0');
}
else if (s[i] == '+' || s[i] == '-') { // a - b == a + (-b)
ret += c *num;
num = 0;
c = (s[i] == '+' ? 1 : -1);
}
else if (s[i] == '(') {
num = DFS(s, ++i);
}
else if (s[i] == ')') {
return ret += (c * num);
}
++i;
}
return ret;
}
};