676. Implement Magic Dictionary

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
66
67
68
69
70
71
72
73
74
75
76
class MagicDictionary {

private static class Trie {

private static class TrieNode {
private final TrieNode[] children;
private boolean end;

public TrieNode() {
this.children = new TrieNode[26];
}
}

private final TrieNode root;

public Trie() {
this.root = new TrieNode();
}

public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
int offset = word.charAt(i) - 'a';
if (node.children[offset] == null) {
node.children[offset] = new TrieNode();
}
node = node.children[offset];
}
node.end = true;
}

public boolean magicSearch(String word) {
return dfs(root, word, 0, false);
}

private boolean dfs(TrieNode node, String word, int index, boolean replaced) {
if (index == word.length()) {
return replaced && node.end;
}

int offset = word.charAt(index) - 'a';
if (node.children[offset] != null && dfs(node.children[offset], word, index + 1, replaced)) {
return true;
} else if (!replaced) {
for (char c = 'a'; c <= 'z'; c++) {
if (c == word.charAt(index)) {
continue;
}
offset = c - 'a';
if (node.children[offset] != null && dfs(node.children[offset], word, index + 1, true)) {
return true;
}
}
}

return false;
}
}

private final Trie trie;

public MagicDictionary() {
this.trie = new Trie();
}

public void buildDict(String[] dictionary) {
for (String word : dictionary) {
trie.insert(word);
}
}

public boolean search(String searchWord) {
return trie.magicSearch(searchWord);
}

}

References

676. Implement Magic Dictionary
剑指 Offer II 064. 神奇的字典