forked from seanprashad/leetcode-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path211_Add_and_Search_Word.java
54 lines (42 loc) · 1.23 KB
/
211_Add_and_Search_Word.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
classWordDictionary {
classTrieNode {
privateTrieNode[] children;
privatebooleanisWord;
publicTrieNode() {
children = newTrieNode[26];
isWord = false;
}
}
privateTrieNoderoot;
publicWordDictionary() {
root = newTrieNode();
}
publicvoidaddWord(Stringword) {
TrieNodecurr = root;
for (charc : word.toCharArray()) {
if (curr.children[c - 'a'] == null) {
curr.children[c - 'a'] = newTrieNode();
}
curr = curr.children[c - 'a'];
}
curr.isWord = true;
}
publicbooleansearch(Stringword) {
returnhelper(word, 0, root);
}
privatebooleanhelper(Stringword, intidx, TrieNodet) {
if (idx >= word.length()) {
returnt.isWord;
}
charc = word.charAt(idx);
if (c == '.') {
for (inti = 0; i < 26; i++) {
if (t.children[i] != null && helper(word, idx + 1, t.children[i])) {
returntrue;
}
}
returnfalse;
}
returnt.children[c - 'a'] != null && helper(word, idx + 1, t.children[c - 'a']);
}
}