Java, 1ms, 15 lines of code, using Stack


  • 5
    Y
    public boolean isValid(String s) {
    		if(s == null || "".equals(s)) return false;
    		char[] ch = s.toCharArray();
    		if((ch.length & 1) == 1) return false;
    		Stack<Character> st = new Stack<Character>();
    		for(int i = 0; i < ch.length; i++){
    			if(st.isEmpty())
    				st.push(ch[i]);
    			else{
    				if((ch[i] == ')' && st.peek() == '(') || 
    						(ch[i] == ']' && st.peek() == '[') || 
    						(ch[i] == '}' && st.peek() == '{')){
    					st.pop();
    					continue;
    				} else
    					st.push(ch[i]);
    			}
    		}
    		return st.isEmpty();
    }

Log in to reply
 

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