这种题都要设置一个符号位的变量
224. Basic Calculator
设置数值和符号两个变量,遇到左括号将数值和符号加进栈中
class Solution { public: int calculate(string s) { stack<int> st; int res = 0,flag = 1; for(int i = 0;i < s.size();i++){ if(s[i] >= '0' && s[i] <= '9'){ int num = 0; while(i < s.size() && s[i] >= '0' && s[i] <= '9'){ num = num*10 + flag * (s[i] - '0'); i++; } res += num; i--; } else 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(); } } return res; } };
227. Basic Calculator II
乘除法有优先级,这个时候需要将这些数值弹出
与上一题不同,这个题是把所有的结果存入进stack中
class Solution { public: int calculate(string s) { long res = 0,num = 0; char op = '+'; stack<int> st; for(int i = 0;i < s.size();i++){ if(s[i] >= '0' && s[i] <= '9') num = num * 10 + s[i] - '0'; if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || i == s.size() - 1){ if(op == '+') st.push(num); if(op == '-') st.push(-num); if(op == '*' || op == '/'){ int tmp = op == '*' ? st.top() * num : st.top() / num; st.pop(); st.push(tmp); } op = s[i]; num = 0; } } while(!st.empty()){ res += st.top(); st.pop(); } return res; } };