import java.util.*; public class Solution { private Stack<Character> opStack = new Stack<>(); private Stack<Integer> numStack = new Stack<>(); /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve (String s) { // write code here if (s == null || s.length() < 1) { throw new IllegalArgumentException("Bad param!"); } s = s.replaceAll(" ", ""); s += ")"; char[] arr = s.toCharArray(); int n = arr.length; opStack.push('('); for (int i = 0; i < n; i++) { char ch = arr[i]; if (ch == '(') { opStack.push('('); } else if (ch >= '0' && ch <= '9') { int num = ch - '0'; while (i + 1 < n && arr[i + 1] >= '0' && arr[i + 1] <= '9') { i++; num = num * 10 + (arr[i] - '0'); } numStack.push(num); } else if (ch == '+' || ch == '/' || ch == '-' || ch == '*') { while (opLevel(ch) <= opLevel(opStack.peek())) { popStackCompute(); } opStack.push(ch); } else if (ch == ')') { while (opStack.peek() != '(') { popStackCompute(); } opStack.pop(); } } return numStack.pop(); } private void popStackCompute() { int num2 = numStack.pop(); int num1 = numStack.pop(); char op = opStack.pop(); if (op == '+') { numStack.push(num1 + num2); } else if (op == '-') { numStack.push(num1 - num2); } else if (op == '/') { numStack.push(num1 / num2); } else if (op == '*') { numStack.push(num1 * num2); } } private int opLevel(char op) { switch (op) { case '/': case '*': return 2; case '+': case '-': return 1; case '(': return 0; } return 0; } }