Pretty java solution for valid parentheses


  • 0
    M
        public boolean isValid(String s) {
        Stack<Character> open = new Stack<Character>();
        Map<Character, Character> pairs = new HashMap<Character, Character>();
        pairs.put('(', ')');
        pairs.put('{', '}');
        pairs.put('[', ']');
        
        for(int i = 0; i< s.length(); i++){
            	switch(s.charAt(i)){
            	case '(':
            	case '{':
            	case '[':
            		open.push(s.charAt(i));
            		break;
            	case ')':
            	case '}':
            	case ']':
            		if(open.isEmpty()) return false;
            		if(pairs.get(open.pop()) != s.charAt(i)) return false;
            		break;
            	default: //let other characters fall out
        	}
        }
    	
    	return open.empty();
    }

Log in to reply
 

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