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
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
for (String string : tokens) {
int res = 0;
if (string.equals("+") || string.equals("-") || string.equals("*") || string.equals("/")) {
int b = stack.pop();
int a = stack.pop();
if (string.equals("+")) {
res += (a + b);
} else if (string.equals("-")) {
res += (a - b);
} else if (string.equals("*")) {
res += (a * b);
} else {
res += (a / b);
}
stack.push(res);
} else {
stack.push(Integer.valueOf(string));
}
}
return stack.pop();
}
}
本文介绍如何使用栈来解析并求值逆波兰表达式,包括正则表达式的使用和算法实现。
306

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



