150 Evaluate Reverse Polish Notation
链接:https://leetcode.com/problems/evaluate-reverse-polish-notation/
问题描述: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
Hide Tags Stack
这个问题就是计算表达式的简单版本,因为数据和运算符已经直接给出,假如给出一个字符串那么难度会更高。题目解题思路如下,每当遇到数字则压栈,遇到运算符则取栈顶两个元素进行运算,运算结果压栈。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> data;
int k1,k2;
for(int i=0;i<tokens.size();i++)
{
if(tokens[i]=="/")
{
k1=data.top();
data.pop();
k2=data.top();
data.pop();
data.push(k2/k1);
continue;
}
else if(tokens[i]=="*")
{
k1=data.top();
data.pop();
k2=data.top();
data.pop();
data.push(k2*k1);
continue;
}
else if(tokens[i]=="+")
{
k1=data.top();
data.pop();
k2=data.top();
data.pop();
data.push(k2+k1);
continue;
}
else if(tokens[i]=="-")
{
k1=data.top();
data.pop();
k2=data.top();
data.pop();
data.push(k2-k1);
continue;
}
data.push(atoi(tokens[i].c_str()));
}
return data.top();
}
};