Java easy-understanding solution


  • 2
    Y
    public int calculate(String s) {
        Stack<String> stack = new Stack<String>();
        int result = 0;
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == ' ') continue;
            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++; continue;
                    } 
                    else break;
                }
                stack.push(s.substring(i, j));
                i = j - 1;
            }else if(s.charAt(i) == ')'){
            	int temp = 0;
                while(!stack.peek().equals("(")){
                    String value = stack.pop();
                    String sign = "+";
                    if(!stack.isEmpty() && !stack.peek().equals("("))	sign = stack.pop();
                    switch (sign){
                        case "+" : temp += Integer.valueOf(value); break;
                        case "-" : temp -= Integer.valueOf(value); break;
                    }
                }
                if(stack.peek().equals("(")) stack.pop();
                stack.push(String.valueOf(temp));
            }else{
                stack.push(s.substring(i, i + 1));
            }
        }
        while(!stack.isEmpty()){
        	String value = stack.pop();
            String sign = "+";
            if(!stack.isEmpty())	sign = stack.pop();
            switch (sign){
                case "+" : result += Integer.valueOf(value); break;
                case "-" : result -= Integer.valueOf(value); break;
            }
        }
        return result;
    }

  • 0
    K

    why i = j - 1 ?


  • 0
    Y
    This post is deleted!

  • 0
    Y

    cuz if the if condition s.charAt(i) >= '0' && s.charAt(i) <= '9' end, it will execute i++, so you have to use j - 1


Log in to reply
 

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