题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*; // 类似的题目:https://www.nowcoder.com/discuss/454321545557635072?sourceSSR=users // mark: // 1. 将[ { 都替换为 ),使用replace函数 replaceAll是正则替换 同时需要重新赋值回去 否则值不变 // 2. 循环从[0, length],字符串末尾添加一个标识符# 防止最后一位是数字的情况 保证最后一个数字能够入栈 // 3. 由于2步骤,所以在判断输入的字符类型时,最后不能是else,需要是else-if (c == ')') // 4. 注意判断是否是负数 // 5. 各个符号的优先级 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String str = in.nextLine(); int length = str.length(); str = str.replace("[", "("); str = str.replace("]", ")"); str = str.replace("{", "("); str = str.replace("}", ")"); Stack<Integer> numStack = new Stack<>(); Stack<Character> opStack = new Stack<>(); String numStr = ""; // 从 0 到 length for (int i = 0; i <= length; i++) { // 字符串末尾添加标识符 否则 如果最后一个字符是数字 那么它将无法入栈 char c = (i == length) ? '#' : str.charAt(i); if (Character.isDigit(c)) { numStr += c; } else { if (numStr.length() > 0) { numStack.push(Integer.valueOf(numStr)); numStr = ""; } if (c == '+' || c == '-') { // 注意判断是否是 负数 if (c == '-' && (i == 0 || str.charAt(i - 1) == '(' )) { numStr = "-"; continue; } while (!opStack.isEmpty() && ((opStack.peek() == '+') || (opStack.peek() == '-') || (opStack.peek() == '*') || (opStack.peek() == '/'))) { char c1 = opStack.pop(); int num2 = numStack.pop(); int num1 = numStack.pop(); numStack.push(calc(c1, num1, num2)); } // 压入 + 或 - opStack.push(c); } else if (c == '*' || c == '/') { opStack.push(c); } else if (c == '(') { opStack.push(c); } else if (c == ')'){ while (!opStack.isEmpty() && (opStack.peek() != '(')) { char c1 = opStack.pop(); int num2 = numStack.pop(); int num1 = numStack.pop(); numStack.push(calc(c1, num1, num2)); } // 弹出( opStack.pop(); } } } while (!opStack.isEmpty()) { char c = opStack.pop(); int num2 = numStack.pop(); int num1 = numStack.pop(); numStack.push(calc(c, num1, num2)); } System.out.println(numStack.pop()); } } public static int calc(char c, int num1, int num2) { switch (c) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; default: return 0; } } }