18ms Java solution with Stack, beats 91%


  • 0
    Y
    public int calculate(String s) {
            if (s == null || s.isEmpty()) {
                return 0;
            }
    
            Stack<Integer> stack = new Stack<>();
            int result = 0;
            int number = 0;
            int op = 0;
            for (char c : s.toCharArray()) {
                if (c == ' ') {
                    continue;
                }
    
                if (Character.isDigit(c)) {
                    number = number * 10 + c - '0';
                } else {
                    if (c == '+' || c == '-') {
                        result = calc(result, op, number);
                        if (!stack.isEmpty()) {
                            result = calc(stack.pop(), stack.pop(), result);
                        }
                    } else if (op <= 1) {
                        stack.push(op);
                        stack.push(result);
                        result = number;
                    } else {
                        result = calc(result, op, number);
                    }
                    op = toOp(c);
                    number = 0;
                }
            }
    
            result = calc(result, op, number);
            if (op > 1) {
                result = calc(stack.pop(), stack.pop(), result);
            }
    
            return result;
        }
    
        private int toOp(char c) {
            switch (c) {
                case '+': return 0;
                case '-': return 1;
                case '*': return 2;
                case '/': return 3;
                default:
                    throw new IllegalArgumentException("Invalid op");
            }
        }
    
        private int calc(int l, int op, int r) {
            switch (op) {
                case 0: return l + r;
                case 1: return l - r;
                case 2: return l * r;
                case 3: return l / r;
                default:
                    throw new IllegalArgumentException("Invalid op");
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.