Java solution with an operator stack and an operand stack


  • 0
    J

    use the tech in compilers. maybe an over kill for such simple calculator. but straight forward.

            Stack<Integer> operands = new Stack<>();
            Stack<Character> operators = new Stack<>();
            int idx = 0, len = s.length();
            while (idx < len) {
                char c = s.charAt(idx);
                idx++;
                if (c >= '0' && c <= '9') {
                    int number = c - '0';
                    while (idx < len) {
                        c = s.charAt(idx);
                        if (c >= '0' && c <= '9') {
                            number = number * 10 + (c - '0');
                            idx++;
                        } else break;
                    }
                    operands.push(number);
                    if (!operators.isEmpty() && operators.peek() != '(') {
                        char op = operators.pop();
                        int right = operands.pop();
                        int left = operands.pop();
                        operands.push(op == '+' ? left + right : left - right);
                    }
                } else if (c == '+' || c == '-' || c == '(') {
                    operators.push(c);
                } else if (c == ')') {
                    boolean getLeft = false;
                    while (operators.size() > 0) {
                        char op = operators.pop();
                        if (op == '(') {
                            if (getLeft) {
                                operators.push('(');
                                break;
                            }
                            getLeft = true;
                            continue;
                        }
                        int right = operands.pop();
                        int left = operands.pop();
                        int res = op == '+' ? left + right : left - right;
                        operands.push(res);
                    }
                }
            }
            
            while (operators.size() > 0) {
                char op = operators.pop();
                int right = operands.pop();
                int left = operands.pop();
                int res = op == '+' ? left + right : left - right;
                operands.push(res);
            }
            return operands.pop();
        }
    

Log in to reply
 

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