import java.util.*; public class PolandNotation { public static void main(String[] args) { String expression = "1+((2+3)*4)-5"; //将中缀表达式分割保存到ArrayList 1+((2+3)*4)-5"-> [1, +, (, (, 2, +, 3, ), *, 4, ), -, 5] List<String> list = toInfixExpressionList(expression); //中缀表达式转换为后缀表达式[1, +, (, (, 2, +, 3, ), *, 4, ), -, 5]->[1, 2, 3, +, 4, *, +, 5, -] List<String> temp = parseSuffixExpressionList(list); //16 System.out.println(calNum(temp)); } //1+((2+3)*4)-5"-> [1, +, (, (, 2, +, 3, ), *, 4, ), -, 5] private static List<String> toInfixExpressionList(String expression) { List<String> res = new ArrayList<>(); int length = expression.length(); String temp = ""; for (int i = 0; i < length; i++) { char ch = expression.charAt(i); if (Arrays.asList('+', '-', '*', '/', '(', ')').contains(ch)) { if (temp != "") { res.add(temp); temp = ""; } res.add(String.valueOf(ch)); } else { temp += ch; } } //将最后一位数字保存 res.add(temp); return res; } //将中缀表达式转换为后缀表达式 public static List<String> parseSuffixExpressionList(List<String> ls) { Stack<String> s1 = new Stack<>(); List<String> s2 = new ArrayList<>(); for (String item : ls) { if (item.matches("\\d+")) { s2.add(item); } else if (item.equals("(")) { s1.push(item); } else if (item.equals(")")) { while (!s1.peek().equals("(")) { s2.add(s1.pop()); } //删除左括号 s1.pop(); } else { while (!s1.isEmpty() && getOperationValue(s1.peek()) >= getOperationValue(item)) { s2.add(s1.pop()); } s1.push(item); } } while (!s1.isEmpty()) { s2.add(s1.pop()); } return s2; } //获取操作符合优先级别 public static int getOperationValue(String item) { return Arrays.asList("*", "/").contains(item) ? 2 : Arrays.asList("+", "-").contains(item) ? 1 : 0; } /** * 完成计算 * @param list * @return */ private static Integer calNum(List<String> list) { Stack<Integer> stack = new Stack<Integer>(); for (String item : list) { //判断是否是数字 if (!item.matches("\\d+")) { int num1 = stack.pop(); int num2 = stack.pop(); int res = 0; switch (item) { case "+": res = num1 + num2; break; case "-": res = num2 - num1; break; case "*": res = num1 * num2; break; case "/": res = num2 / num1; break; default: break; } stack.push(res); } else { stack.push(Integer.valueOf(item)); } } return stack.pop(); } }
后缀表达式计算