Simple Accepted Java solution.


  • 10
    P

    I think the code is clear to understand.

    public boolean isValid(String s) {
        char[] chars = s.toCharArray();
        Map<Character,Character> pairs = new HashMap<Character,Character>();
        pairs.put('(', ')');
        pairs.put('{', '}');
        pairs.put('[', ']');
        
        Stack<Character> stack = new Stack<Character>();
        for (char c:chars) {
        	if (pairs.containsKey(c)) {
        		stack.push(pairs.get(c));
        	} else {
        		if (stack.isEmpty() || c != stack.pop()) return false;
        	}
        }
        return stack.isEmpty();
    }

Log in to reply
 

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