题目:https://leetcode-cn.com/problems/basic-calculator/
参考:https://leetcode-cn.com/problems/basic-calculator/solution/lioneycli-yong-zhan-jian-dan-qiu-jie-by-lioney/
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
class Solution {
public:
int calculate(string s) {
int n = s.length();
long long res = 0,flag = 1,tmp = 0;
stack<long long> st;
for(int i = 0;i < n;i++) {
if(s[i] == '+') flag = 1;
else if(s[i] == '-') flag = -1;
else if(s[i] == '(') {
st.push(res);st.push(flag);
res = 0;flag = 1;
}
else if(s[i] == ')') {
res *= st.top();st.pop();
res += st.top();st.pop();
}
else if('0'<=s[i] && s[i]<='9') {
tmp = 0;
while(i < n && '0'<=s[i] && s[i]<='9')
tmp = tmp*10+s[i]-'0',i++;
i--;
res += tmp*flag;
}
}
return res;
}
};