-
Notifications
You must be signed in to change notification settings - Fork 0
/
211. Design Add and Search Words Data Structure
59 lines (48 loc) · 1.52 KB
/
211. Design Add and Search Words Data Structure
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
class WordDictionary {
private class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
public TrieNode() {
children = new TrieNode[26];
isEndOfWord = false;
}
}
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
public boolean search(String word) {
return searchInNode(word, root, 0);
}
private boolean searchInNode(String word, TrieNode node, int start) {
for (int i = start; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch == '.') {
for (int j = 0; j < 26; j++) {
if (node.children[j] != null && searchInNode(word, node.children[j], i + 1)) {
return true;
}
}
return false; // No valid path found
} else {
int index = ch - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
}
return node.isEndOfWord;
}
}