-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
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
class WordDictionary {
class TrieNode {
private TrieNode[] children;
private boolean isWord;
public TrieNode() {
children = new TrieNode[26];
isWord = false;
}
}
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (curr.children[c - 'a'] == null) {
curr.children[c - 'a'] = new TrieNode();
}
curr = curr.children[c - 'a'];
}
curr.isWord = true;
}
public boolean search(String word) {
return helper(word, 0, root);
}
private boolean helper(String word, int idx, TrieNode t) {
if (idx >= word.length()) {
return t.isWord;
}
char c = word.charAt(idx);
if (c == '.') {
for (int i = 0; i < 26; i++) {
if (t.children[i] != null && helper(word, idx + 1, t.children[i])) {
return true;
}
}
return false;
}
return t.children[c - 'a'] != null && helper(word, idx + 1, t.children[c - 'a']);
}
}