Java Valid Paranthesis


  • 0
    T

    public boolean isValid(String s) {

    	if (s == "")
    		return true; // empty string is technically valid
    	if (s.length() % 2 == 1)
    		return false; // odd length wont work
    
    	boolean valid = true;
    	Stack<Character> open = new Stack<>(); // close stack
    	Stack<Character> close = new Stack<>(); // open stack
    
    	for (int i = 0; i < s.length(); i++) {
    		if (s.charAt(i) == '(') {
    			open.push('(');
    			close.push(')');
    
    		}
    
    		else if (s.charAt(i) == '{') {
    			close.push('}');
    			open.push('{');
    		}
    
    		else if (s.charAt(i) == '[') {
    			close.push(']');
    			open.push('[');
    		}
    
    		else if (s.charAt(i) == ')') {
    			if (!close.isEmpty() && close.pop() == ')' && !open.isEmpty() && open.pop() == '(')
    				continue;
    
    			else {
    				valid = false;
    				break;
    			}
    		}
    
    		else if (s.charAt(i) == ']') {
    			if (!close.isEmpty() && close.pop() == ']' && !open.isEmpty() && open.pop() == '[')
    				continue;
    			else {
    				valid = false;
    				break;
    			}
    		}
    
    		else if (s.charAt(i) == '}') {
    			if (!close.isEmpty() && close.pop() == '}' && !open.isEmpty() && open.pop() == '{')
    				continue;
    			else {
    				valid = false;
    				break;
    			}
    		}
    
    	}
    
    	if (open.isEmpty() && close.isEmpty() && valid)
    		return true;
    	else
    		return valid;
    
    }

Log in to reply
 

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