Java short solution, java8 new syntax


  • 3
    J
    public class Solution {
    
    private int num = 0;
    private int ans = 0;	
    private int sign = 1;
    
    public int calculate(String s) {
    	Stack<Integer> signs = new Stack<Integer>();
    	s = "(" + s + ")";  // Every "s" can be viewed as "+(s)". Since we use "sign = 1" 
    						// to represent the proceeding "+", skip it from the string.
    	
    	s.chars().filter((c) -> ("0123456789+-()".contains(String.valueOf((char) (c))))).forEach((c) -> {
    		if (c >= '0' && c <= '9') {
    			num = 10 * num + c - '0';
    		} else if (c == '+' || c == '-') {
    			ans = ans + signs.peek() * sign * num;
    			num = 0;
    			sign = (c == '+') ? 1 : -1;
    		} else if (c == '(') {
    			if (!signs.isEmpty())
    				signs.push(sign * signs.peek());
    			else
    				signs.push(sign);
    			sign = 1;
    		} else if (c == ')') {
    			ans = ans + signs.pop() * sign * num;
    			num = 0;
    			sign = 1;
    		}
    	});
    	return ans;
    }	
    

    )


Log in to reply
 

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