原题如下:
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这道题不算太难,需要借助stack完成运算,当遍历vector中的字符串时,当遇到数字时直接将字符串转化成数字后入栈,当遇到运算符时,需要出栈两个数并进行相应运算,然后将结果写入stack中,这里需要注意出栈的第二个数时第一个运算数。另外C++中将string转化成int的方法是:atoi(s.c_str())。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
int len = tokens.size();
if(len <= 0)
return 0;
stack<int>s;
for(int i = 0; i < len; i++){
if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){
s.push(atoi(tokens[i].c_str()));
}
else
{
int a = s.top();
s.pop();
int b = s.top();
s.pop();
if(tokens[i] == "+")
s.push(a + b);
else if(tokens[i] == "-")
s.push(b - a);
else if(tokens[i] == "*")
s.push(a * b);
else
s.push(b / a);
}
}
return s.top();
}
};