题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.ArrayDeque; import java.util.Deque; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { /** * 中缀表达式转后缀表达式 */ public static String toSuffix(String expression) { // 操作符栈 Deque<Character> stack = new ArrayDeque<>(); StringBuilder suffix = new StringBuilder(); // 后缀表达式字符串 int i = 0; while (i < expression.length()) { char ch = expression.charAt(i); switch (ch) { case '+': case '-': if (ch == '-') { if (i == 0) { suffix.append(0).append(" "); stack.push('-'); i++; break; } else { char c = expression.charAt(i - 1); if (c == '(') { suffix.append(0).append(" "); stack.push('-'); i++; break; } } } while (!stack.isEmpty() && stack.peek() != '(') { suffix.append(stack.pop()).append(" "); } stack.push(ch); i++; break; case '*': case '/': while (!stack.isEmpty() && (stack.peek() == '*' || stack.peek() == '/')) { suffix.append(stack.pop()).append(" "); } stack.push(ch); i++; break; case '(': stack.push(ch); i++; break; case ')': Character symbol = stack.pop(); while (symbol != null && symbol != '(') { suffix.append(symbol).append(" "); symbol = stack.pop(); } i++; break; default: // 遇到数字 while (i < expression.length() && Character.isDigit(ch)) { suffix.append(ch); i++; if (i < expression.length()) { ch = expression.charAt(i); } } suffix.append(" "); // 添加空格作为数值之间的分隔符 } } while (!stack.isEmpty()) { suffix.append(stack.pop()).append(" "); } return suffix.toString(); } /** * 计算后缀表达式的值 */ public static int calculate(String suffixExpression) { // 操作数栈 Deque<Integer> stack = new ArrayDeque<>(); int ans = 0; for (int i = 0; i < suffixExpression.length(); i++) { char ch = suffixExpression.charAt(i); if (Character.isDigit(ch)) { ans = 0; while (ch != ' ') { // 数字字符转为整数值 ans = ans * 10 + ch - '0'; ch = suffixExpression.charAt(++i); } stack.push(ans); // 整数对象入栈 } else { if (ch != ' ') { // 出栈两个操作数,注意出栈次序 int y = stack.pop(); int x = stack.pop(); switch (ch) { case '+': ans = x + y; break; case '-': ans = x - y; break; case '*': ans = x * y; break; case '/': ans = x / y; break; } stack.push(ans); // 运算结果入栈 } } } return stack.pop(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String expression = sc.next(); expression = expression.replaceAll("\\[", "(") .replaceAll("]", ")") .replaceAll("\\{", "(") .replaceAll("}", ")"); String suffixExpression = toSuffix(expression); int ans = calculate(suffixExpression); System.out.println(ans); } }