424 · Evaluate Reverse Polish Notation
Description
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, , /. Each operand may be an integer or another expression.
If you use python, you should use int(a / b) to calc the / operation rather than a // b.
Example
Example 1:
Input: [“2”, “1”, “+”, “3”, ""]
Output: 9
Explanation: [“2”, “1”, “+”, “3”, “*”] -> (2 + 1) * 3 -> 9
Example 2:
Input: [“4”, “13”, “5”, “/”, “+”]
Output: 6
Explanation: [“4”, “13”, “5”, “/”, “+”] -> 4 + 13 / 5 -> 6
解法1:递归
以[“5”, “3”, “4”, “-”, “+”]为例,一开始第0层调用helper(tokens, 4),从右往左扫描,遇到”+“号,先第一层递归调用helper(tokens, 3),这里会遇到"-",第二层递归调用helper(tokens,2),此时遇到4和3,得到3-4=-1,然后再递归调用helper(tokens, 1),得到5,然后得到5+(-1)=4。注意递归参数op要用引用,因为每次递归都会-1。
class Solution {
public:
/**
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
int evalRPN(vector<string> &tokens) {
int op = tokens.size() - 1;
return helper(tokens, op);
}
private:
int helper(vector<string>& tokens, int& op) {
string s = tokens[op];
if (s != "+" && s != "-" && s != "*" && s != "/") return stoi(s);
int v1 = helper(tokens, --op);
int v2 = helper(tokens, --op);
if (s == "+") return v1 + v2;
if (s == "-") return v2 - v1;
if (s == "*") return v1 * v2;
return v2 / v1;
}
};
解法2:用stack,这个解法最好理解。
以[“5”, “3”, “4”, “-”, “+”]为例,,从左往右扫描,5,3,4先顺序压栈,遇到"-“,弹出4和3,然后把3-4的结果-1压栈,然后遇到”+",弹出-1和5,得到5+(-1)的结果为4。
class Solution {
public:
/**
* @param tokens: The Reverse Polish Notation
* @return: the value
*/
int evalRPN(vector<string> &tokens) {
int len = tokens.size();
stack<int> stk;
for (int i = 0; i < len; i++) {
string s = tokens[i];
if (s != "+" && s != "-" && s != "*" && s != "/") {
stk.push(stoi(s));
continue;
}
int result = 0;
int top1 = stk.top(); stk.pop();
int top2 = stk.top(); stk.pop();
switch (s[0]) {
case '+':
result = top1 + top2;
break;
case '-':
result = top2 - top1;
break;
case '*':
result = top1 * top2;
break;
case '/':
result = top2 / top1;
break;
default:
break;
}
stk.push(result);
}
int ret = stk.top(); stk.pop();
return ret;
}
};
5万+

被折叠的 条评论
为什么被折叠?



