Simple Java Solution


  • -1
    U
    import java.util.Stack;
    
    public class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character> ();
    				
    		if (s == null || s.isEmpty()) {
    			return true;
    		}
    		
    		for (int i = 0; i<s.length(); i++) {
    			
    			Character c = s.charAt(i);
    			
    			if (shouldPush(c)) {
    				stack.push(c);
    			}
    			else if (shouldPop(c)) {
    				
    				if (stack.isEmpty()) {
    					return false;
    				}
    				
    				Character popped = stack.pop();
    				
    				if (!isPair(popped, c)) {
    					return false;
    				}
    				
    			}
    			
    		}
    		
    		if (!stack.isEmpty()) {
    			return false;
    		}
    		
    		return true;
        }
        
        public boolean shouldPush(Character c) {
    		
    		if (c == '(' || c == '{' | c == '[') {
    			return true;
    		}
    		else {
    			return false;
    		}
    		
    	}
    	
    	public boolean shouldPop(Character c) {
    		
    		if (c == ')' || c == '}' | c == ']') {
    			return true;
    		}
    		else {
    			return false;
    		}
    		
    	}
    	
    	public boolean isPair(Character c1, Character c2) {
    		
    		if ( (c1 == '(' && c2 == ')') ||
    				(c1 == '{' && c2 == '}') || 
    					(c1 == '[' && c2 == ']')) {
    			return true;
    		}
    		else {
    			return false;
    		}
    		
    	}
        
    }

Log in to reply
 

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