Simple Java solution using Stack and Map.


  • 0
    M
    public boolean isValid(String s) {
            
            if (s == null || s.equals("")) {
                return true;
            }
            
            Map<Character, Character> map = new HashMap<Character, Character>();
            map.put(')','(');
            map.put('}','{');
            map.put(']','[');
            
            Stack<Character> brackets = new Stack<Character>();
            
            int i = 0;
            
            while (i < s.length()) {
                if (! map.containsKey(s.charAt(i))) {
                    // Implies it is an opening bracket and hence needs to go to the top of the stack
                    brackets.push(s.charAt(i));
                } else if (brackets.isEmpty() || map.get(s.charAt(i)) != brackets.pop()) {
                    return false;
                }
                i++;
            }
            return brackets.isEmpty();
        }
    

Log in to reply
 

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