问题描述
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
解决方案
class Solution {
public:
pair<int, int> popTwoValues( stack<int> &tokens ) {
int t1 = tokens.top();
tokens.pop();
int t2 = tokens.top();
tokens.pop();
return { t1, t2 };
}
int evalRPN(vector<string> &tokens) {
stack<int> exprStack;
for( const auto &elem : tokens ) {
if( elem == "+" ) {
auto p = popTwoValues( exprStack );
exprStack.push( p.second + p.first );
} else if( elem == "-" ) {
auto p = popTwoValues( exprStack );
exprStack.push( p.second - p.first );
} else if( elem == "*" ) {
auto p = popTwoValues( exprStack );
exprStack.push( p.second * p.first );
} else if( elem == "/" ) {
auto p = popTwoValues( exprStack );
exprStack.push( p.second / p.first );
} else {
exprStack.push( atoi( elem.c_str() ) );
}
}
return exprStack.top();
}
};