Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . Example 1: Input: "1 + 1" Output: 2 Example 2: Input: " 2-1 + 2 " Output: 3 Example 3: Input: "(1+(4+5+2)-3)+(6+8)" Output: 23 https://www.youtube.com/watch?v=9c0WHgIsk5g&t=41s http://www.cnblogs.com/grandyang/p/4570699.html // use one stack // more general : use two stacks, one is for the prev res // another one is for the sign Use one stack https://leetcode.com/problems/basic-calculator/discuss/62361/Iterative-Java-solution-with-stack Use two stacks 不是我写的, 还有不明白的 class Solution { public int calculate(String s) { if (s == null || s.length() == 0) return 0; Stack<Integer> nums = new Stack<>(); // the stack that stores numbers Stack<Character> ops = new Stack<>(); // the stack that stores operators (including parentheses) int num = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ' ') continue; if (Character.isDigit(c)) { num = c - '0'; // iteratively calculate each number while (i < s.length() - 1 && Character.isDigit(s.charAt(i+1))) { num = num * 10 + (s.charAt(i+1) - '0'); i++; } nums.push(num); num = 0; // reset the number to 0 before next calculation } else if (c == '(') { ops.push(c); } else if (c == ')') { // do the math when we encounter a ')' until '(' while (ops.peek() != '(') nums.push(operation(ops.pop(), nums.pop(), nums.pop())); ops.pop(); // get rid of '(' in the ops stack // ? 不知道这个precedence 在做什么? } else if (c == '+' || c == '-' || c == '*' || c == '/') { while (!ops.isEmpty() && precedence(c, ops.peek())) nums.push(operation(ops.pop(), nums.pop(),nums.pop())); ops.push(c); } } while (!ops.isEmpty()) { nums.push(operation(ops.pop(), nums.pop(), nums.pop())); } return nums.pop(); } private static int operation(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; // assume b is not 0 } return 0; } // helper function to check precedence of current operator and the uppermost operator in the ops stack // 这个 helper function, 不懂在做什么 private static boolean precedence(char op1, char op2) { if (op2 == '(' || op2 == ')') return false; if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false; return true; } }