Simple JAVA solution with one stack.


  • 0
    M

    Code is easy and self explanatory, I would recommend to read code first and other things later.

    1. Simplest check is length of the input string. If its not even it is not valid for sure. (As every opening bracket/parenthesis will have closing pair.)
    2. Regular Expression check for other symbols, characters and numbers.
    3. Keeping opening bracket/parenthesis in stack and nullifying it when we get closing bracket/parenthesis of same pair. (Shortcircuiting this operation to return false if any of the pair doesn't match) Additional check is to check stack is not empty.
    4. Last and important is to check the stack is empty or not as it indicates pair does not found.
     public boolean isValid(String input) {
            if(!input.matches("[\\[|{|(|)|}|\\]]*") || !(input.length()%2==0)){
    		return false;
    	}
    	Stack<Character> stack = new Stack<Character>();
    	for(int i=0;i<input.length();i++){
    		char next = input.charAt(i);
    		if(next=='[' || next=='{' || next=='('){
    			stack.push(next);
    		}else{
    			if(stack.isEmpty() || !comparePair(stack.pop(), next)){
    				return false;
    			}
    		}
    	}
    	return stack.isEmpty();
    }
        
    private boolean comparePair(char prev,char next){
    	switch(prev){
    		case '[': return next==']';
    		case '{': return next=='}';
    		case '(': return next==')';
    	}
    	return false;
    }
    

    Please let me know if there is any other easy method or improvement is the same.

    Thanks,
    Malhar


Log in to reply
 

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