Evaluate Reverse Polish Notation
标签(空格分隔): leetcode 算法
题目:
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> s;
for (
vector<string>::size_type i =
0; i < tokens.size(); ++i) {
string& str = tokens[i];
if (str.size()) {
if (
isdigit(str[
0]) ||
(str[
0] ==
'+' && str.size() >
1) ||
(str[
0] ==
'-' && str.size() >
1)) {
s.push(atoi(str.c_str()));
}
else if (s.size() >=
2) {
int rhs = s.top();
s.pop();
int lhs = s.top();
s.pop();
switch(str[
0]) {
case '+':
s.push(lhs + rhs);
break;
case '-':
s.push(lhs - rhs);
break;
case '*':
s.push(lhs * rhs);
break;
case '/':
if (rhs ==
0) {
return 0;
}
else {
s.push(lhs / rhs);
break;
}
default:
return 0;
}
}
else {
return 0;
}
}
}
if (s.size() ==
1) {
int ret = s.top();
s.pop();
return ret;
}
else {
return 0;
}
}
};