题目来源
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
计算逆波兰表达式的值,这个感觉比较简单,就是利用一个栈,把数字都进栈,然后碰到一个符号就出栈两个数字,把结果进栈,直到表达式结束或栈空。
就是这么简陋的写法,不过至少能AC是不
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int n = tokens.size();
stack<int> s;
for (int i=0; i<n; i++) {
if (tokens[i] == "+") {
int x1 = s.top();
s.pop();
int x2 = s.top();
s.pop();
s.push(x1 + x2);
}
else if (tokens[i] == "-") {
int x1 = s.top();
s.pop();
int x2 = s.top();
s.pop();
s.push(x2 - x1);
}
else if (tokens[i] == "*") {
int x1 = s.top();
s.pop();
int x2 = s.top();
s.pop();
s.push(x1 * x2);
}
else if (tokens[i] == "/") {
int x1 = s.top();
s.pop();
int x2 = s.top();
s.pop();
s.push(x2 / x1);
}
else {
int x = stoi(tokens[i]);
s.push(x);
}
}
return s.top();
}
};
有点长,写的简洁一点…
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int n = tokens.size();
stack<int> s;
for (int i=0; i<n; i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
int x1 = s.top();
s.pop();
int x2 = s.top();
s.pop();
if (tokens[i] == "+")
s.push(x1 + x2);
else if (tokens[i] == "-")
s.push(x2 - x1);
else if (tokens[i] == "*")
s.push(x1 * x2);
else
s.push(x2 / x1);
}
else {
int x = stoi(tokens[i]);
s.push(x);
}
}
return s.top();
}
};
不过写简洁了,时间变长了一些,不过其实复杂度是一样的是不。