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
此题的目的在于计算逆波兰表示法的值。
思路:
1.利用栈解决问题。
2.定义一个栈,遍历给定的字符串,遍历过程中,每遇到一个数,就将此数压入栈中,当遇到一个运算符时,就从栈顶取出两个数进行相应的运算,并将运算结果压入栈中。
3.当遍历完成后,栈顶的数即为最后的结果值。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
int x,y;
stack<string> s;
for (auto token : tokens) {
if (!is_operator(token)) {
s.push(token);
}
else {
y = stoi(s.top());
s.pop();
x = stoi(s.top());
s.pop();
if (token[0] == '+') x += y;
else if (token[0] == '-') x -= y;
else if (token[0] == '*') x *= y;
else x /= y;
s.push(to_string(x));
}
}
return stoi(s.top());
}
private:
bool is_operator(const string &op) {
return op.size() == 1 && string("+-*/").find(op) != string::npos;
}
};