原题链接
Note:
题目名字看的花哨,但是实际上是后缀表达式,用栈模拟操作一下就行了
代码如下:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for(int i = 0; i < tokens.size(); i ++){
if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){
int num = 0,flag = 1;
for(int j = 0; j < tokens[i].size(); j ++){
if(tokens[i][j] == '-'){
flag = -1;
continue;
}
num = num * 10 + (tokens[i][j] - '0');
}
s.push(num * flag);
}else {
int ans = 0;
int b = s.top();
s.pop();
int a = s.top();
s.pop();
if(tokens[i] == "+")
ans = a + b;
else if(tokens[i] == "-")
ans = a - b;
else if(tokens[i] == "*")
ans = a * b;
else if(tokens[i] == "/")
ans = a / b;
s.push(ans);
}
}
return s.top();
}
};
|