问题描述
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();
}
};
本文介绍了一种解决逆波兰表达式求值问题的方法。利用栈数据结构处理加减乘除运算,通过遍历表达式的各个元素并进行相应操作,最终得出表达式的计算结果。
310

被折叠的 条评论
为什么被折叠?



