forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.java
73 lines (55 loc) · 1.6 KB
/
0211-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
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/
class WordDictionary {
Node root;
private class Node {
char value;
boolean isWord;
Node[] children;
public Node(char value) {
this.value = value;
isWord = false;
children = new Node[26];
}
}
public WordDictionary() {
root = new Node('\0');
}
public void addWord(String word) {
Node curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (curr.children[ch - 'a'] == null) {
curr.children[ch - 'a'] = new Node(ch);
}
curr = curr.children[ch - 'a'];
}
curr.isWord = true;
}
// TC O(m^2)
public boolean search(String word) {
return searchHelper(word, root, 0);
}
private boolean searchHelper(String word, Node curr, int index) {
for (int i = index; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch == '.') {
for (Node temp : curr.children) {
if (temp != null && searchHelper(word, temp, i + 1)) {
return true;
}
}
return false;
}
if (curr.children[ch - 'a'] == null) {
return false;
}
curr = curr.children[ch - 'a'];
}
return curr.isWord;
}
}