面试常用算法——解析逆波兰式
public class Test03 { public static void main(String[] args) { String[] s = { "2", "1", "+", "3", "*" }; // 逆波兰式 Stack<Double> stack = new Stack<Double>(); // 栈 Double a, b; for (int i = 0; i < s.length; i++) { switch (s[i]) { //这个需要jdk1.7以上版本支持 case "+": a = stack.pop(); b = stack.pop(); stack.push(a + b); break; case "-": a = stack.pop(); b = stack.pop(); stack.push(a-b); break; case "*": a = stack.pop(); b = stack.pop(); stack.push(a*b); break; case "/": a = stack.pop(); b = stack.pop(); stack.push(a/b); break; default: stack.push(Double.parseDouble(s[i])); } } System.out.println("result = "+stack.pop()); } }
改进部分代码,看起来更简洁了点
public class Test03 { public static void main(String[] args) { String[] s = { "2", "1", "+", "3", "*" }; // 逆波兰式 String operator = "+-*/"; Stack<Double> stack = new Stack<Double>(); // 栈 Double a, b; for (int i = 0; i < s.length; i++) { if (!operator.contains(s[i])) stack.push(Double.parseDouble(s[i])); else { a = stack.pop(); b = stack.pop(); switch (operator.indexOf(s[i])) { case 0: stack.push(a + b); break; case 1: stack.push(a - b); break; case 2: stack.push(a * b); break; case 3: stack.push(a / b); break; } } } System.out.println("result = " + stack.pop()); } }