-
Notifications
You must be signed in to change notification settings - Fork 5
/
211. Design Add and Search Words Data Structure.java
91 lines (75 loc) · 2.67 KB
/
211. Design Add and Search Words Data Structure.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.Arrays;
class WordDictionary {
private static class TrieNode {
char character;
TrieNode[] children;
boolean isEndofWord;
public TrieNode(char c) {
this.character = c;
this.children = new TrieNode[26];
this.isEndofWord = false;
Arrays.fill(children, null);
}
}
private static class Trie {
private TrieNode trieRootNode;
public Trie() {
this.trieRootNode = new TrieNode('\0');
}
public void add(String word) {
char[] letters = word.toCharArray();
TrieNode current = this.trieRootNode;
for (char letter : letters) {
int index = letter - 'a';
if (current.children[index] == null) {
current.children[index] = new TrieNode(letter);
}
current = current.children[index];
}
current.isEndofWord = true;
}
public boolean search(TrieNode trieRootNode, String word) {
TrieNode current = trieRootNode;
if (current == null)
return false;
char[] letters = word.toCharArray();
for (int index = 0; index < letters.length; index++) {
char letter = letters[index];
if (letter == '.') {
for (int ci = 0; ci < current.children.length; ci++) {
if (current.children[ci] == null)
continue;
if (search(current.children[ci], word.substring(index + 1)))
return true;
}
} else {
int cindex = letter - 'a';
if (current.children[cindex] == null)
return false;
current = current.children[cindex];
}
}
return (current != null) && current.isEndofWord;
}
private boolean searchUtil(WordDictionary.TrieNode current, String word) {
return (word != null && word.length() > 0 && current != null) && search(current, word)
&& current.isEndofWord;
}
}
private Trie trie;
public WordDictionary() {
trie = new Trie();
}
public void addWord(String word) {
trie.add(word);
}
public boolean search(String word) {
return trie.search(trie.trieRootNode, word);
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/