问题描述:
/**
* 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
*/
这个问题之前面试刚刚遇见过。其实上面的英文描述不用看,单看给的例子就大致明白了。一个字符串数组里面,如果有操作符,那么操作符优先与它左边的两个数进行操作运算,再把结果放入其中。依次类推。看到这里,可以想到借助栈stack可以完美解决这个问题。一开始先把数字压入栈,遇见操作符“+”“-”“*”“/”以后,连续弹出两个数,进行运算,然后再把结果压入栈,然后再进行压栈操作。具体代码如下:
public int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<Integer>();
int size = tokens.length;
for (int i = 0; i < size; i++) {
if (isDigital(tokens[i])) {//遇见数字则压入
st.push(Integer.parseInt(tokens[i]));
} else {//遇见操作符,弹出两个数字进行运算,再将结果压入栈
st.push(calc(st.pop(), st.pop(), tokens[i]));
}
}
return st.pop();
}
private Integer calc(Integer num2, Integer num1, String op) {
switch (op.charAt(0)) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return 0;
}
}
private boolean isDigital(String s) {//判断压入的是数字还是操作符
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
return true;
}