题目:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators
and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the eval
built-in
library function.
思路:
唉,自己写的代码总是很冗长。。。还是把网上这个精炼的算法贴在这里,帮大家一起分析一下吧:由于四个运算符可以分为两个优先级,所以我们可以考虑采用两次扫描:1)计算所有的*和/,并且将所有参与+和-运算的操作数(有可能是*和/的运算结果)都放在一个数组(栈)中;2)计算所有的+和-的结果。为了方便,这里使用了一个小技巧:如果是-,则将操作数取反,并存入数组中。这样的好处是所有的操作符都可以被认为是+,所以就不需要在数组中进行额外存储了。
代码:
class Solution {
public:
int calculate(string s) {
s += "+";
stack<int> st;
char old = '+';
int left = 0;
for (int i = 0; i < s.size(); ++i) {
if (isdigit(s[i]) || isspace(s[i])) {
continue;
}
int val = stoi(s.substr(left, i - left));
if (old == '+' || old == '-') {
st.push(old == '+' ? val : -val);
}
else {
st.top() = (old == '*' ? st.top() * val : st.top() / val);
}
old = s[i];
left = i + 1;
}
int ret = 0;
while (!st.empty()) {
ret += st.top();
st.pop();
}
return ret;
}
};