题目:
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 calcWithOperator(const string& op, int l, int r) {
char c = *op.c_str();
switch (c) {
case '+':
return l + r;
case '-':
return l - r;
case '*':
return l * r;
case '/':
return l / r;
}
return 0;
}
bool isStringOperator(const string& str) {
if (str.length() != 1) {
return false;
}
char c = *str.c_str();
return c == '+' || c == '-' || c == '*' || c == '/';
}
int evalRPN(vector<string>& tokens) {
stack<int> stackNum;
for (int i = 0; i != tokens.size(); ++i) {
const string str = tokens[i];
if (isStringOperator(str)) {
if (stackNum.size() < 2) {
return -1;
} else {
int r = stackNum.top();
stackNum.pop();
int l = stackNum.top();
stackNum.pop();
int result = calcWithOperator(str, l, r);
stackNum.push(result);
}
} else {
stackNum.push(atoi(str.c_str()));
}
}
if (stackNum.size() != 1) {
return -1;
} else {
return stackNum.top();
}
}
};