Accepted Java solution using Stack.


  • 0
    O
    
        public int calculate(String s) {
        	Stack<Integer> stack = new Stack<Integer>();
        	s = s.replaceAll(" ", "");
        	int num = 0;
        	char sign = '+';
        	for(char ch: s.toCharArray()) {
        		if(ch-48 >= 0 && ch-48 <= 9) {
        			num = num*10+(ch-48);
        		} else {
    	    		if (sign == '+') {
    	    			stack.push(num);
    	    		} else if (sign == '-') {
    	    			stack.push(-num);
    	    		} else if (sign == '*') {
    	    			stack.push(stack.pop()*num);
    	    		} else {
    	    			stack.push(stack.pop()/num);
    	    		}
    				num = 0;
    				sign = ch;
        		}
        	}
    		if (sign == '+') {
    			stack.push(num);
    		} else if (sign == '-') {
    			stack.push(-num);
    		} else if (sign == '*') {
    			stack.push(stack.pop()*num);
    		} else {
    			stack.push(stack.pop()/num);
    		}
        	int result = 0;
        	while(!stack.isEmpty()) {
        		result += stack.pop();
        	}
        	return result;
        }
    

Log in to reply
 

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