Java solution with stream API, stack and reg expression


  • 0
    F
    1. we use stack to handle ( and )
    2. for everything inside ( and ), we convert - to +-, like 5-2 => 5+-2 . we then replace the (...) with the calculated number
    3. The difficult part may be +- and --, we use reg expression to convert them to - and +
     public class Solution {
        	private Map<Character, BiFunction<Integer, Integer, Integer>> map = new HashMap<>();
    	{
    		map.put('+', (x, y) -> x + y);
    		map.put('-', (x, y) -> x - y);
    	}
    
    	public int calculate(String s) {
    		if (s == null || s.isEmpty()) {
    			return 0;
    		}		
    		return doCalcuate("(" + s + ")");
    	}
    
    	private int doCalcuate(String s) {
    		Deque<Integer> stack = new ArrayDeque<>();
    		int i = 0;
    
    		while (i < s.length()) {
    			char sc = s.charAt(i);
    			if (sc == '(') {
    				stack.push(i);
    			} else if (sc == ')') {
    				if (stack.isEmpty()) {
    					throw new IllegalArgumentException("wrong bracket");
    				}
    				int start = stack.pop();
    				int v = internalCalcuate(s, start + 1, i - 1);
    				// take 0..start-1 v i+1...end
    				String upper = s.substring(0, start) + v;				
    				s = upper + s.substring(i + 1);
    				i = upper.length() - 1;
    			}
    			i++;
    		}
    		return Integer.valueOf(s);
    	}
    
    	private int internalCalcuate(String s, int start, int end) {
    		String sub = s.substring(start, end + 1);
    		
    		sub=sub.replaceAll(" ", "");		
    		sub=sub.replaceAll("\\+-", "-");
    		sub=sub.replaceAll("--", "\\+");
    		sub=sub.replaceAll("-", "\\+-");		
    		String[] splitted = sub.split("\\+");
    		return Arrays.stream(splitted).filter(x->!x.isEmpty()).mapToInt(x->Integer.valueOf(x)).sum();
    	}
    }

Log in to reply
 

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