Accepted Java Solution using stacks


  • 0
    D

    '''

    public class Solution {
    public int calculate(String s) {
    Stack<Integer> digits = new Stack<>();
    Stack<Character> symbols = new Stack<>();
    StringBuilder sb;

        for(int i = s.length() - 1; i >= 0; i--){
            if(Character.isDigit(s.charAt(i))){
                sb = new StringBuilder();
                while(i >= 0 && Character.isDigit(s.charAt(i))){
                    sb.insert(0, s.charAt(i));
                    i--;
                }
                i++;
                digits.push(Integer.valueOf(sb.toString()));
            }
            else if(s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' || s.charAt(i) == '/'){
                if(symbols.isEmpty())
                    symbols.push(s.charAt(i));
                /* If the current opertaors precedence is less than the stack top operator's precedence */
                else if((s.charAt(i) == '+' || s.charAt(i) == '-') && (symbols.peek() == '*' || symbols.peek() == '/')){
                    while(!symbols.isEmpty() && (s.charAt(i) == '+' || s.charAt(i) == '-') && (symbols.peek() == '*' || symbols.peek() == '/')){
                        int num1 = digits.pop();
                        int num2 = digits.pop();
                        char op = symbols.pop();
                        int result = perform_operation(num1, num2, op);
                        digits.push(result);
                    }
                    i++;    // check the condition for this operator again (since the stack might be empty and the condition is already mentioned above)
                }
                else
                    symbols.push(s.charAt(i));
            }
        }
        while(!symbols.isEmpty()){
            char op = symbols.pop();
            int num1 = digits.pop();
            int num2 = digits.pop();
            digits.push(perform_operation(num1, num2, op));
        }
        return digits.pop();
    }
    
    private int perform_operation(int num1, int num2, char op){
        if(op == '+')
            return num1 + num2;
        if(op == '*')
            return num1 * num2;
        if(op == '-')
            return num1 - num2;
        if(op == '/')
            return num1 / num2;
        return -1;
    }
    

    }

    '''


Log in to reply
 

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