http://bookshadow.com/weblog/2016/10/16/leetcode-word-squares/
https://zhuhan0.blogspot.com/2017/09/leetcode-425-word-squares.html
Store all words into a trie. Iterate through the words.
https://discuss.leetcode.com/topic/63417/181-ms-java-solution-intuitive-backtracking
http://bookshadow.com/weblog/2016/10/16/leetcode-word-squares/
X. Using Trie
https://discuss.leetcode.com/topic/63516/my-java-solution-using-trie
X. https://segmentfault.com/a/1190000008454085
X. http://www.cnblogs.com/grandyang/p/6006000.html
那么根据以往的经验,对于这种要打印出所有情况的题的解法大多都是用递归来解,那么这题的关键是根据前缀来找单词,我们如果能利用合适的数据结构来建立前缀跟单词之间的映射,使得我们能快速的通过前缀来判断某个单词是否存在,这是解题的关键。对于建立这种映射,这里主要有两种方法,一种是利用哈希表来建立前缀和所有包含此前缀单词的集合之前的映射,第二种方法是建立前缀树Trie,顾名思义,前缀树专门就是为这种问题设计的。那么我们首先来看第一种方法,用哈希表来建立映射的方法,我们就是取出每个单词的所有前缀,然后将该单词加入该前缀对应的集合中去,然后我们建立一个空的nxn的char矩阵,其中n为单词的长度,我们的目标就是来把这个矩阵填满,我们从0开始遍历,我们先取出长度为0的前缀,即空字符串,由于我们在建立映射的时候,空字符串也和每个单词的集合建立了映射,然后我们遍历这个集合,用遍历到的单词的i位置字符,填充矩阵mat[i][i],然后j从i+1出开始遍历,对应填充矩阵mat[i][j]和mat[j][i],然后我们根据第j行填充得到的前缀,到哈希表中查看有没单词,如果没有,就break掉,如果有,则继续填充下一个位置。最后如果j==n了,说明第0行和第0列都被填好了,我们再调用递归函数,开始填充第一行和第一列,依次类推,直至填充完成
Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence
["ball","area","lead","lady"]
forms a word square because each word reads the same both horizontally and vertically.
Note:
- There are at least 1 and at most 1000 words.
- All words will have the exact same length.
- Word length is at least 1 and at most 5.
- Each word contains only lowercase English alphabet a-z.
Example 1:
Example 2:
X. DFShttps://zhuhan0.blogspot.com/2017/09/leetcode-425-word-squares.html
Store all words into a trie. Iterate through the words.
- For each word:
- create a new list. Add the word into the list.
- Search the trie for all the words that have the correct prefix. For each of these words:
- Add it to the list.
- Continue searching for the next prefix recursively.
- The recursion reaches its base case when the size of the list is equal to the length of a word. In this case, we've found a word square.
Say there are n words, the words' length is l, and each trie node has c children on average. buildTrie() takes O(ln). wordSquares() helper method takes O(c^l). So the for loop takes O(nc^l). The overall time complexity is O(ln + nc^l).
class TrieNode { TrieNode[] children; boolean isWord; TrieNode() { children = new TrieNode[26]; } } public List<List<String>> wordSquares(String[] words) { TrieNode root = buildTrie(words); List<List<String>> squares = new ArrayList<>(); for (String word : words) { List<String> square = new ArrayList<>(); square.add(word); wordSquares(root, word.length(), square, squares); } return squares; } private TrieNode buildTrie(String[] words) { TrieNode root = new TrieNode(); for (String word : words) { TrieNode current = root; for (char c : word.toCharArray()) { int index = c - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isWord = true; } return root; } private TrieNode search(TrieNode root, String prefix) { TrieNode current = root; for (char c : prefix.toCharArray()) { int index = c - 'a'; if (current.children[index] == null) { return null; } current = current.children[index]; } return current; } private void wordSquares(TrieNode root, int len, List<String> square, List<List<String>> squares) { if (square.size() == len) { squares.add(new ArrayList<>(square)); return; } String prefix = getPrefix(square, square.size()); TrieNode node = search(root, prefix); if (node == null) { return; } List<String> children = new ArrayList<>(); getChildren(node, prefix, children); for (String child : children) { square.add(child); wordSquares(root, len, square, squares); square.remove(square.size() - 1); } } private String getPrefix(List<String> square, int index) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < index; i++) { sb.append(square.get(i).charAt(index)); } return sb.toString(); } private void getChildren(TrieNode node, String s, List<String> children) { if (node.isWord) { children.add(s); return; } for (int i = 0; i < 26; i++) { if (node.children[i] != null) { getChildren(node.children[i], s + (char) ('a' + i), children); } } }https://discuss.leetcode.com/topic/63516/explained-my-java-solution-using-trie-126ms-16-16
My first approach is brute-force, try every possible word sequences, and use the solution of Problem 422 (https://leetcode.com/problems/valid-word-square/) to check each sequence. This solution is straightforward, but too slow (TLE).
A better approach is to check the validity of the word square while we build it.
Example:
We know that the sequence contains 4 words because the length of each word is 4.
Every word can be the first word of the sequence, let's take
Which word could be the second word? Must be a word start with
Which word could be the third word? Must be a word start with
What about the last word? Must be a word start with
Example:
["area","lead","wall","lady","ball"]
We know that the sequence contains 4 words because the length of each word is 4.
Every word can be the first word of the sequence, let's take
"wall"
for example.Which word could be the second word? Must be a word start with
"a"
(therefore "area"
), because it has to match the second letter of word "wall"
.Which word could be the third word? Must be a word start with
"le"
(therefore "lead"
), because it has to match the third letter of word "wall"
and the third letter of word "area"
.What about the last word? Must be a word start with
"lad"
(therefore "lady"
). For the same reason above.
The picture below shows how the prefix are matched while building the sequence.
In order for this to work, we need to fast retrieve all the words with a given prefix. There could be 2 ways doing this:
- Using a hashtable, key is prefix, value is a list of words with that prefix.
- Trie, we store a list of words with the prefix on each trie node.
class TrieNode {
List<String> startWith;
TrieNode[] children;
TrieNode() {
startWith = new ArrayList<>();
children = new TrieNode[26];
}
}
class Trie {
TrieNode root;
Trie(String[] words) {
root = new TrieNode();
for (String w : words) {
TrieNode cur = root;
for (char ch : w.toCharArray()) {
int idx = ch - 'a';
if (cur.children[idx] == null)
cur.children[idx] = new TrieNode();
cur.children[idx].startWith.add(w);
cur = cur.children[idx];
}
}
}
List<String> findByPrefix(String prefix) {
List<String> ans = new ArrayList<>();
TrieNode cur = root;
for (char ch : prefix.toCharArray()) {
int idx = ch - 'a';
if (cur.children[idx] == null)
return ans;
cur = cur.children[idx];
}
ans.addAll(cur.startWith);
return ans;
}
}
public List<List<String>> wordSquares(String[] words) {
List<List<String>> ans = new ArrayList<>();
if (words == null || words.length == 0)
return ans;
int len = words[0].length();
Trie trie = new Trie(words);
List<String> ansBuilder = new ArrayList<>();
for (String w : words) {
ansBuilder.add(w);
search(len, trie, ans, ansBuilder);
ansBuilder.remove(ansBuilder.size() - 1);
}
return ans;
}
private void search(int len, Trie tr, List<List<String>> ans,
List<String> ansBuilder) {
if (ansBuilder.size() == len) {
ans.add(new ArrayList<>(ansBuilder));
return;
}
int idx = ansBuilder.size();
StringBuilder prefixBuilder = new StringBuilder();
for (String s : ansBuilder)
prefixBuilder.append(s.charAt(idx));
List<String> startWith = tr.findByPrefix(prefixBuilder.toString());
for (String sw : startWith) {
ansBuilder.add(sw);
search(len, tr, ans, ansBuilder);
ansBuilder.remove(ansBuilder.size() - 1);
}
}
https://discuss.leetcode.com/topic/63532/121ms-java-solution-using-trie-and-backtracking TrieNode root = new TrieNode();
public List<List<String>> wordSquares(String[] words) {
List<List<String>> ans = new ArrayList<>();
if(words.length == 0) return ans;
buildTrie(words);
int length = words[0].length();
findSquare(ans, length, new ArrayList<>());
return ans;
}
private void findSquare(List<List<String>> ans, int length, List<String> temp) {
if(temp.size() == length) {
ans.add(new ArrayList<>(temp));
return;
}
int index = temp.size();
StringBuilder sb = new StringBuilder();
for(String s : temp) {
sb.append(s.charAt(index));
}
String s = sb.toString();
TrieNode node = root;
for(int i = 0; i < s.length(); i++) {
if(node.next[s.charAt(i) - 'a'] != null) {
node = node.next[s.charAt(i) - 'a'];
} else {
node = null;
break;
}
}
if(node != null) {
for(String next : node.words) {
temp.add(next);
findSquare(ans, length, temp);
temp.remove(temp.size() - 1);
}
}
}
private void buildTrie(String[] words) {
for(String word : words) {
TrieNode node = root;
char[] array = word.toCharArray();
for(char c : array) {
node.words.add(word);
if(node.next[c - 'a'] == null) {
node.next[c - 'a'] = new TrieNode();
}
node = node.next[c - 'a'];
}
node.words.add(word);
}
}
class TrieNode {
TrieNode[] next = new TrieNode[26];
List<String> words = new ArrayList<>();
}
https://discuss.leetcode.com/topic/63417/181-ms-java-solution-intuitive-backtracking
http://bookshadow.com/weblog/2016/10/16/leetcode-word-squares/
深度优先搜索(DFS)+ 剪枝(Pruning)
X. Using Trie
https://discuss.leetcode.com/topic/63516/my-java-solution-using-trie
class TrieNode {
List<String> startWith;
TrieNode[] children;
TrieNode() {
startWith = new ArrayList<>();
children = new TrieNode[26];
}
}
class Trie {
TrieNode root;
Trie(String[] words) {
root = new TrieNode();
for (String w : words) {
TrieNode cur = root;
for (char ch : w.toCharArray()) {
int idx = ch - 'a';
if (cur.children[idx] == null)
cur.children[idx] = new TrieNode();
cur.children[idx].startWith.add(w);
cur = cur.children[idx];
}
}
}
List<String> findPrefix(String prefix) {
List<String> ans = new ArrayList<>();
TrieNode cur = root;
for (char ch : prefix.toCharArray()) {
int idx = ch - 'a';
if (cur.children[idx] == null)
return ans;
cur = cur.children[idx];
}
ans.addAll(cur.startWith);
return ans;
}
}
public List<List<String>> wordSquares(String[] words) {
List<List<String>> ans = new ArrayList<>();
if (words == null || words.length == 0)
return ans;
int n = words.length;
int len = words[0].length();
Trie trie = new Trie(words);
List<String> ansBuilder = new ArrayList<>();
for (String w : words) {
ansBuilder.add(w);
search(words, n, len, trie, ans, ansBuilder);
ansBuilder.remove(ansBuilder.size() - 1);
}
return ans;
}
private void search(String[] ws, int n, int len, Trie tr,
List<List<String>> ans, List<String> ansBuilder) {
if (ansBuilder.size() == len) {
ans.add(new ArrayList<>(ansBuilder));
return;
}
int idx = ansBuilder.size();
StringBuilder prefix = new StringBuilder();
for (String s : ansBuilder)
prefix.append(s.charAt(idx));
List<String> startWith = tr.findPrefix(prefix.toString());
for (String sw : startWith) {
ansBuilder.add(sw);
search(ws, n, len, tr, ans, ansBuilder);
ansBuilder.remove(ansBuilder.size() - 1);
}
}
https://discuss.leetcode.com/topic/64770/java-dfs-trie-54-ms-98-so-far/2X. https://segmentfault.com/a/1190000008454085
w a l l
a r e a
l e a d
l a d y
在给定的词典里,找到一些单词,组成一个square, 第i行和第i列一样。
(0,0) 这个点找到满足条件的,我们选择w。
(0,1) 我们要满足wa, a都可以作为开头的部分。
(0,2) 我们要满足wal, l都可以作为开头的部分。
(0,0) 这个点找到满足条件的,我们选择w。
(0,1) 我们要满足wa, a都可以作为开头的部分。
(0,2) 我们要满足wal, l都可以作为开头的部分。
按照代码的逻辑,走一遍test case, 填写好prefix[]每一步被更新的样子。
第0行。
开始 prefix[root, root, root, root]
(0, 0) prefix[root, root, root, root] (root.w, root.w) root[0] = w, root[0] = w
(0, 1) prefix[w, root, root, root] (w.a, root.a) root[0] = wa, root[1] = a
(0, 2) prefix[wa, a, root, root] (wa.l, root.l) root[0] = wal, root[2] = l
(0, 3) prefix[wal, a, l, root] (wal.l, root.l) root[0] = wall, root[3] = l
结束 prefix[wall, a, l, l]
第1行。
开始 prefix[wall, a, l, l]
(1,1) prefix[wall, a, l, l] (a.r, a.r) root[1] = ar, root[1] = ar
(1,2) prefix[wall, ar, l, l] (ar.e, l.e) root[1] = are, root[2] = le
(1,3) prefix[wall, are, le, l] (are.a, l.a) root[1] = area, root[3] =la
结束 prefix[wall, area, le, la]
public class Solution {
class Node{
String word = null;
Node[] kids = new Node[26];
}
private Node root = new Node();
private void buildTrie(String word, Node par){
for(char c: word.toCharArray()){
int idx = c -'a';
if(par.kids[idx] == null) par.kids[idx] = new Node();
par = par.kids[idx];
}
par.word = word;
}
private void findAllSquares(int row , int col, Node[] prefix, List<List<String>> res){
if(row == prefix.length){
List<String> temp = new ArrayList<String>();
for(int i=0; i<prefix.length; i++){
temp.add(prefix[i].word);
}
res.add(temp);
} else if(col < prefix.length){
Node currow = prefix[row];
Node curcol = prefix[col];
for(int i=0; i<26; i++){
if(currow.kids[i] != null && curcol.kids[i] != null){ // 同一层从左向右走的时候
prefix[row] = currow.kids[i]; // prefix[row]会不断增长,直到最后形成以个单词
prefix[col] = curcol.kids[i]; // prefix[col]相应位置长度加一,更新prefix
findAllSquares(row, col+1, prefix, res);
}
}
prefix[row] = currow; // reset back 重新进行下一次的搜索。
prefix[col] = curcol;
} else {
findAllSquares(row+1, row+1, prefix, res);
}
}
public List<List<String>> wordSquares(String[] words) {
List<List<String>> res = new ArrayList<List<String>>();
if(words == null || words.length == 0 || words[0] == null || words[0].length() == 0) return res;
for(String word: words){
buildTrie(word, root);
}
Node[] prefix = new Node[words[0].length()];
Arrays.fill(prefix, root);
findAllSquares(0, 0, prefix, res);
return res;
}
}
那么根据以往的经验,对于这种要打印出所有情况的题的解法大多都是用递归来解,那么这题的关键是根据前缀来找单词,我们如果能利用合适的数据结构来建立前缀跟单词之间的映射,使得我们能快速的通过前缀来判断某个单词是否存在,这是解题的关键。对于建立这种映射,这里主要有两种方法,一种是利用哈希表来建立前缀和所有包含此前缀单词的集合之前的映射,第二种方法是建立前缀树Trie,顾名思义,前缀树专门就是为这种问题设计的。那么我们首先来看第一种方法,用哈希表来建立映射的方法,我们就是取出每个单词的所有前缀,然后将该单词加入该前缀对应的集合中去,然后我们建立一个空的nxn的char矩阵,其中n为单词的长度,我们的目标就是来把这个矩阵填满,我们从0开始遍历,我们先取出长度为0的前缀,即空字符串,由于我们在建立映射的时候,空字符串也和每个单词的集合建立了映射,然后我们遍历这个集合,用遍历到的单词的i位置字符,填充矩阵mat[i][i],然后j从i+1出开始遍历,对应填充矩阵mat[i][j]和mat[j][i],然后我们根据第j行填充得到的前缀,到哈希表中查看有没单词,如果没有,就break掉,如果有,则继续填充下一个位置。最后如果j==n了,说明第0行和第0列都被填好了,我们再调用递归函数,开始填充第一行和第一列,依次类推,直至填充完成
vector<vector<string>> wordSquares(vector<string>& words) { vector<vector<string>> res; unordered_map<string, set<string>> m; int n = words[0].size(); for (string word : words) { for (int i = 0; i < n; ++i) { string key = word.substr(0, i); m[key].insert(word); } } vector<vector<char>> mat(n, vector<char>(n)); helper(0, n, mat, m, res); return res; } void helper(int i, int n, vector<vector<char>>& mat, unordered_map<string, set<string>>& m, vector<vector<string>>& res) { if (i == n) { vector<string> out; for (int j = 0; j < n; ++j) out.push_back(string(mat[j].begin(), mat[j].end())); res.push_back(out); return; } string key = string(mat[i].begin(), mat[i].begin() + i); for (string str : m[key]) { mat[i][i] = str[i]; int j = i + 1; for (; j < n; ++j) { mat[i][j] = str[j]; mat[j][i] = str[j]; if (!m.count(string(mat[j].begin(), mat[j].begin() + i + 1))) break; } if (j == n) helper(i + 1, n, mat, m, res); } }