Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
高频题,one pass。用java自带的FILO的数据结构Stack解决。遍历字符串数组。遇到数字入栈,遇到符号从栈顶取两个元素进行计算并将结果再次入栈。
最后取栈顶为结果。此处不考虑含有特殊符号的问题,所以没有进行异常处理
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
Stack<String> res = new Stack<String>();
for(String str : tokens) {
if(str.equals("+") || str.equals("-") || str.equals("*") ||
str.equals("/")) {
int sec = Integer.parseInt(res.pop());
int fir = Integer.parseInt(res.pop());
if(str.equals("+")) res.push(String.valueOf(fir + sec));
if(str.equals("-")) res.push(String.valueOf(fir - sec));
if(str.equals("*")) res.push(String.valueOf(fir * sec));
if(str.equals("/")) res.push(String.valueOf(fir / sec));
} else {
res.push(str);
}
}
return res.isEmpty() ? 0 : Integer.parseInt(res.pop());
}
}