Simple Java Solution (beats 98.8 %)


  • 0
    K

    public class Solution {

    public boolean isValid(String s) {
        /* only half of the string length is needed for the validation.*/
        char[] stack = new char[s.length() / 2];  
        /* stack pointer. */
        int sp = 0;
        
        /* open:  '(', '{', '['. */
        /* close: ')', '}', ']'. */
        for (char ch: s.toCharArray()) {
            char close = 0;
            /**
             * if the current char is open, 
             *      find the corresponding close char.
             * else 
             *      close remains 0.
             */
            switch (ch) {
                case '(': close = ')'; break;
                case '[': close = ']'; break;
                case '{': close = '}'; break;
                default: break;
            }
            /* means the current char is open. */
            if (close != 0) {
                /* terminate if the stack is filled. (half chars of the string are checked.)*/
                if (sp >= stack.length) return false;
                /* put the close char in the stack. */
                stack[sp++] = close;
            }
            /* means the current char is close. */
            else {
                /* terminate if the last open char does not pair with current close char. */
                if (sp < 1 || stack[sp - 1] != ch) return false;
                /* pop the stack. */
                sp--;
            }
        }
        /* stack is empty. */
        return sp == 0;
    }
    

    }


  • 0

    public boolean isValid(String s) {

    	char[] arr = new char[s.length()];
    	int top = -1;
    
    	if (null != s && s.length() != 1) {
    
    		for (char p : s.toCharArray()) {
    
    			if (top == -1 || p == '(' || p == '{' || p == '[') {
    				arr[++top] = p;
    			} else {
    				if ((arr[top] == '(' && p == ')') || (arr[top] == '{' && p == '}')
    						|| (arr[top] == '[' && p == ']')) {
    					arr[top--] = 0;
    
    				} else {
    					return false;
    				}
    
    			}
    
    		}
    
    		if (top == -1) {
    			return true;
    		}
    	}
    
    	return false;
    }
    

Log in to reply
 

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