LC.P211[添加与搜索单词-数据结构设计]

方法一:Trie+DFS

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
58
59
60
61
62
63
64
65
class WordDictionary {

Trie trie;

public WordDictionary() {
trie = new Trie();
}

public void addWord(String word) {
trie.add(word);
}

public boolean search(String word) {
return dfs(word, 0, trie);
}

private boolean dfs(String word, int index, Trie node) {
if (index == word.length()) return node.isEnd;
char c = word.charAt(index);
if (c == '.') {
for (int i = 0; i < 26; ++i) {
Trie child = node.next[i];
if (child != null && dfs(word, index + 1, child)) {
return true;
}
}
} else {
int u = c - 'a';
Trie child = node.next[u];
if (child != null && dfs(word, index + 1, child)) {
return true;
}
}
return false;
}

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

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

public void add(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;
}
}
}

/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/