[Google] LeetCode 150 Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, and /
. Each operand may be an integer or another expression.
Note that division between two integers should truncate toward zero.
It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.
Solution
直接用 \(stack\) 维护即可
点击查看代码
class Solution {
private:
stack<int> s;
bool check_opt(string s){
if(s=="+"|| s=="-"||s=="*"||s=="/")return true;
return false;
}
public:
int evalRPN(vector<string>& tokens) {
int n = tokens.size();
for(int i=0;i<n;i++){
if(check_opt(tokens[i])){
//cout<<s.top()<<endl;
int num1 = (s.top());s.pop();
int num2 = (s.top());s.pop();
string tmp = tokens[i];
if(tmp=="+")s.push(num1+num2);
else if(tmp=="-")s.push(num2-num1);
else if(tmp=="*")s.push(num1*num2);
else s.push(num2/num1);
}
else{
s.push(stoi(tokens[i]));
}
}
return s.top();
}
};