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 evalRPN(vector<string>& tokens) {
stack<int> opera;
int sum;
for(int i=0;i<tokens.size();i++)
{
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int one = opera.top();
opera.pop();
int two = opera.top();
opera.pop();
if(tokens[i] == "+")
{
opera.push(one+two);
}
else if(tokens[i] == "-")
{
opera.push(two-one);
}
else if(tokens[i] == "*")
{
opera.push(one*two);
}
else if(tokens[i] == "/")
{
opera.push(two/one);
}
}
else
{
opera.push(atoi(tokens[i].c_str()));
}
}
return opera.top();
}
};