Word Square

422 Valid Word Square

Given a sequence of words, check whether it forms a valid word square.

A sequence of words forms a valid word square if the kth row and column read the exact same string

public boolean validWordSquare(List<String> words) {
   for(int i=0; i<words.size(); i++){
       for(int j=0; j<words.get(i).length(); j++){
           if(j>=words.size() || 
              i>= words.get(j).length() || 
              words.get(i).charAt(j) != words.get(j).charAt(i))
               return false;
       }
   }
    return true;
}

425 Word Square II

Given a set of words (without duplicates), find all word squares you can build from them.

  • Build a trie, record the prefix string list in every node

  • search the word by word square rule

Last updated

Was this helpful?