题目:
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> st;
for (int i = 0; i < tokens.size(); ++i) {
if (isOperator(tokens[i])) {
int second = st.top();
st.pop();
int first = st.top();
st.pop();
st.push(getValue(first, second, tokens[i][0]));
}
else {
st.push(stoi(tokens[i]));
}
}
return st.top();
}
private:
bool isOperator(const string &s) {
if (s == "+" || s == "-" || s == "*" || s == "/") {
return true;
}
else {
return false;
}
}
int getValue(int first, int second, char c) {
if (c == '+') {
return first + second;
}
else if (c == '-') {
return first - second;
}
else if (c == '*') {
return first * second;
}
else if (c == '/') {
return first / second;
}
else {
return -1;
}
}
};