题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
中缀-后缀-计算后缀,注意一元减的情况 (@)
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); List<String> infix = new ArrayList<>(); StringBuilder numberBuilder = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isDigit(ch)) { numberBuilder.append(ch); } else { if (numberBuilder.length() > 0) { infix.add(numberBuilder.toString()); numberBuilder = new StringBuilder(); } infix.add(ch + ""); } } if (numberBuilder.length() > 0) { infix.add(numberBuilder.toString()); numberBuilder = new StringBuilder(); } // infix -> postfix List<String> postfix = new ArrayList<>(); Stack<String> opStack = new Stack<>(); List<String> order = new ArrayList<>(); order.add("("); order.add("+"); order.add("-"); order.add("*"); order.add("/"); order.add("@"); for (int i = 0; i < infix.size(); i++) { String part = infix.get(i); if (part.equals("+") || part.equals("-") || part.equals("*") || part.equals("/")) { if (part.equals("-")) { if (i == 0) { part = "@"; } else { String last = infix.get(i - 1); if (last.equals("+") || last.equals("-") || last.equals("*") || last.equals("/") || last.equals("(")) { part = "@"; } } } while (true) { if (opStack.size() == 0) { opStack.push(part); break; } if (order.indexOf(part) > order.indexOf(opStack.peek())) { opStack.push(part); break; } String op = opStack.pop(); postfix.add(op); } } else if (part.equals("(")) { opStack.push(part); } else if (part.equals(")")) { do { String op = opStack.peek(); if (op.equals("(")) { opStack.pop(); break; } else { opStack.pop(); postfix.add(op); } } while (true); } else { postfix.add(part); } } while (opStack.size() > 0) { String op = opStack.pop(); postfix.add(op); } // postfix evaluate Stack<Integer> numberStack = new Stack<>(); for (String part : postfix) { if (part.equals("-")) { int a = numberStack.pop(); int b = numberStack.pop(); numberStack.push(b - a); } else if (part.equals("+")) { int a = numberStack.pop(); int b = numberStack.pop(); numberStack.push(b + a); } else if (part.equals("*")) { int a = numberStack.pop(); int b = numberStack.pop(); numberStack.push(b * a); } else if (part.equals("/")) { int a = numberStack.pop(); int b = numberStack.pop(); numberStack.push(b / a); } else if (part.equals("@")) { int a = numberStack.pop(); numberStack.push(-a); } else { numberStack.push(Integer.parseInt(part)); } } System.out.println(numberStack.pop()); } }