Skip to content

Commit c19845f

Browse files
committed
Design add and search words structure
1 parent b692573 commit c19845f

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// SC: O(n)
2+
// -> n is the length of the given String
3+
// TC: O(n * 26)
4+
// -> n is the length of the given String * the number of alphabets
5+
class TrieNode {
6+
TrieNode[] childNode;
7+
boolean isEndOfWord;
8+
9+
public TrieNode() {
10+
childNode = new TrieNode[26];
11+
isEndOfWord = false;
12+
}
13+
}
14+
15+
class WordDictionary {
16+
17+
private TrieNode root;
18+
19+
public WordDictionary() {
20+
root = new TrieNode();
21+
}
22+
23+
public void addWord(String word) {
24+
TrieNode node = root;
25+
26+
for (char c : word.toCharArray()) {
27+
int idx = c - 'a';
28+
if (node.childNode[idx] == null) {
29+
node.childNode[idx] = new TrieNode();
30+
}
31+
node = node.childNode[idx];
32+
}
33+
node.isEndOfWord = true;
34+
}
35+
36+
public boolean search(String word) {
37+
return searchInNode(word.toCharArray(), 0, root);
38+
}
39+
40+
private boolean searchInNode(char[] word, int idx, TrieNode node) {
41+
if (idx == word.length) return node.isEndOfWord;
42+
43+
char c = word[idx];
44+
45+
if (c == '.') {
46+
for (TrieNode child : node.childNode) {
47+
if (child != null && searchInNode(word, idx+1, child)) return true;
48+
}
49+
return false;
50+
} else {
51+
int childIdx = c - 'a';
52+
if (node.childNode[childIdx] == null) return false;
53+
return searchInNode(word, idx+1, node.childNode[childIdx]);
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)