227. Basic Calculator II
来源: LeetCode 227. Basic Calculator II
题目描述
227. Basic Calculator II
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.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
思路分析
用栈加自定义优先级
代码
class Solution {
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
typedef pair<int, int> PI;
public:
int calculate(string s) {
// stack + priority
// * / -> 2 + - -> 0
// stack_num stack_sign
stack<int>st1;
stack<char>st2;
unordered_map<char, int>mp = {
{'*', 2},
{'/', 2},
{'+', 1},
{'-', 1},
}; // priority
string str;
st1.push(0);
for(auto c:s){
if(c>47 && c<58) str+=c;
else{
if(mp.find(c) == mp.end()) continue;
st1.push(stoi(str)); // 计算得到前面的数字
while(!st2.empty() && mp[c]<=mp[st2.top()]) {
int a = st1.top(); st1.pop();
int b = st1.top(); st1.pop();
// cout << b << st2.top() << a << '=';
st1.push(getval(a, b, st2.top()));
st2.pop();
// cout << st1.top() << endl;
} // 判断优先级运算
st2.push(c);
str = "";
}
}
if(SIZE(str)) st1.push(stoi(str));
while(!st2.empty()){
char c = st2.top(); st2.pop();
int a = st1.top(); st1.pop();
int b = st1.top(); st1.pop();
// cout << b << c << a << '=';
st1.push(getval(a, b, c));
// cout << st1.top() << endl;
}
return st1.top();
}
int getval(int a, int b, char c){
switch(c){
case '*': b *= a;break;
case '/': b /= a;break;
case '+': b += a;break;
case '-': b -= a;
}
return b;
}
};