题意
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:
int compute(stack<int>& istack, string str){
if(istack.size() < 2) return -1;
int val1 = istack.top();
istack.pop();
int val2 = istack.top();
istack.pop();
if(str == "+") return val2 + val1;
else if(str == "-") return val2 - val1;
else if(str == "*") return val2 * val1;
else if(str == "/") return val2 / val1;
else return -1;
}
int evalRPN(vector<string>& tokens) {
stack<int> istack;
for(int i = 0; i < tokens.size(); ++i){
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){
int value = compute(istack,tokens[i]);
istack.push(value);
}else{
istack.push(atoi(tokens[i].c_str()));
}
}
return istack.top();
}
};