Constant space 3ms Java solution


  • 2
    A
    public int calculate(String s) {
        return sub(s, 0, new int[1]);
    }
    private int sub(String s, int start, int[] end){
        int sum = 0;
        int num = 0;
        boolean m = false;
        boolean visited = false;
        for(int i = start; i < s.length()+1; i++){
            char c = ' ';
            if(i < s.length()){
                c = s.charAt(i);
            }
            if(c >= 48 && c <= 57){
                num *= 10;
                num += ((int)c-48);
                visited = false;
            }else{
                if(!visited){
                    if(m){
                        sum -= num;
                        m = false;
                    }else{
                        sum += num;
                    }
                    num = 0;
                    visited = true;
                }
                if(c == 45){
                    m = true;
                }
                if(c == 40){
                    if(m) {
                        sum -= sub(s, i+1, end);
                    }else{
                        sum += sub(s, i+1, end);
                    }
                    m = false;
                    i = end[0]; 
                }
                if(c == 41){
                    end[0] = i;
                    return sum;
                }
            }
        }
        return sum;
    }
    

    }


Log in to reply
 

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