https://leetcode.com/problems/basic-calculator/
用 stack 存储当前运算符:
public class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(1); // add this for case like "1 + 1" int result = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { int j = i + 1; while (j < s.length()) { if (s.charAt(j) >= '0' && s.charAt(j) <= '9') { j++; } else { break; } } int num = Integer.parseInt(s.substring(i, j)); result += stack.pop() * num; i = j - 1; } else if (s.charAt(i) == '+' || s.charAt(i) == '(') { stack.push(stack.peek()); } else if (s.charAt(i) == '-') { stack.push(-1 * stack.peek()); } else if (s.charAt(i) == ')') { stack.pop(); } } return result; } }
也可以用 RPN 做

浙公网安备 33010602011771号