1ms Clear Java Solution using Stack


  • 0
    C
    public boolean isValid(String s) {
       if (s.length() % 2 != 0) {
           return false;
       }
        
       char[] sArr = s.toCharArray();
        
       HashMap<Character, Character> hm = new HashMap<>();
       hm.put(')','(');
       hm.put('}','{');
       hm.put(']','[');
        
       Stack<Character> st = new Stack<>();
        
       for(char c : sArr) {
           if (!hm.containsKey(c)) {
               st.push(c);
           } else {
               if (st.isEmpty() || st.pop() != hm.get(c)) {
                   return false;
               }
            }
         }
        
        return st.isEmpty();
    }

Log in to reply
 

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