LeetCode

Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Java

public class Solution {
    private static final Map<Character, Character> map;
    static {
        Map<Character, Character> temp = new HashMap<Character, Character>();
        temp.put('(', ')');
        temp.put('[', ']');
        temp.put('{', '}');
        map = Collections.unmodifiableMap(temp); 
    }
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();

        for(char c : s.toCharArray()) {
            if(map.containsKey(c)) {
                stack.push(c);
            } else if (stack.isEmpty() || map.get(stack.pop()) != c) {
                return false;
            }
        }

        return stack.isEmpty();
    }
}