Java solution with hashmap


  • 0
    M
        public boolean validWordSquare(List<String> words) {
            if (words == null || words.size() <= 1) return true;
            HashMap<Integer, Character> hm = new HashMap<>();
            int count = 0;
    
            for (String word : words) {
                for (int i = 0; i < word.length(); i++) {
                    if (i > count) hm.put(count * 1000 + i, word.charAt(i));
                    else if (count > i) {
                        if (word.charAt(i) != hm.getOrDefault(i * 1000 + count, ' ')) return false;
                        else hm.remove(i * 1000 + count);
                    }
                }
                count++;
            }
            return hm.size() == 0;
        }
    

Log in to reply
 

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