题目
在反向波兰表示法中计算算术表达式的值。
有效的运算符是+, - ,*,/。 每个操作数可以是整数或另一个表达式。
举例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
分析
其实就是计算符号前相邻两个数的值,再push进入stack,直到循环结束,stack中只会存在一个最终计算的值。
具体思路,以 ["2", "1", "+", "3", "*"]
为例:
stack: 2
-> 1,2
; 遍历到+
,那么pop
出1,2
,相加值为3
,将3push
进入stack
,继续遍历,stack: 3,3
;遍历到*
,取出stack
中的数3,3
,相乘值为9,将结果push
进stack
,继续遍历时发现,数组已经走完了,最后再将stack
中的值pop
出来。
代码
package algorithm018;
import java.util.Stack;
public class Algorithm018 {
public static void main(String[] args) {
// ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
// ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
String[] test1 = {"2", "1", "+", "3", "*"};
System.out.println(evalRPN(test1));
String[] test2 = {"4", "13", "5", "/", "+"};
System.out.println(evalRPN(test2));
}
public static int evalRPN(String[] test) {
String pattern = "+-*/";
String operation1 = "+";
String operation2 = "-";
String operation3 = "*";
String operation4 = "/";
Stack<Integer> stack = new Stack<>();
for(String s : test) {
if(!pattern.contains(s)) {
Integer i = Integer.parseInt(s);
stack.push(i);
}else {
Integer b = stack.pop();
Integer a = stack.pop();
Integer c = 0;
if(s.equals(operation1)) {
c = a + b;
}else if(s.equals(operation2)) {
c = a - b;
}else if(s.equals(operation3)) {
c = a * b;
}else {
c = a / b;
}
stack.push(c);
}
}
return stack.pop();
}
}