LC.P472[连接词]

方法一:Trie+记忆化搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
Trie trie;

public List<String> findAllConcatenatedWordsInADict(String[] words) {
trie = new Trie();
List<String> ans = new ArrayList<>();
Arrays.sort(words, (a, b) -> a.length() - b.length());
for (String word : words) {
int n = word.length();
if (n == 0) continue;
boolean[] visited = new boolean[n];
if (dfs(word, 0, visited)) ans.add(word);
else trie.insert(word);
}
return ans;
}

private boolean dfs(String word, int start, boolean[] visited) {
if (word.length() == start) return true;
if (visited[start]) return false;
visited[start] = true;
Trie node = trie;
for (int i = start; i < word.length(); ++i) {
int u = word.charAt(i) - 'a';
node = node.next[u];
if (node == null) return false;
if (node.isEnd) {
if (dfs(word, i + 1, visited)) {
return true;
}
}
}
return false;
}

private static class Trie {
Trie[] next;
boolean isEnd;

public Trie() {
next = new Trie[26];
isEnd = false;
}

public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); ++i) {
int u = word.charAt(i) - 'a';
if (node.next[u] == null) {
node.next[u] = new Trie();
}
node = node.next[u];
}
node.isEnd = true;
}
}
}