Skip to content

Commit 5b0fd83

Browse files
committed
Two-Hundred-Fourteen Commit: Add Design Add and Search Words Data Structure problem to Trie Section
1 parent 65f5a9c commit 5b0fd83

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package Trie;
2+
3+
// Problem Statement: Design Add and Search Words Data Structure (medium)
4+
// LeetCode Question: 211. Design Add and Search Words Data Structure
5+
6+
public class Problem_3_Design_Add_And_Search_Words_Data_Structure {
7+
8+
class TrieNode {
9+
TrieNode[] children = new TrieNode[26];
10+
boolean isEnd = false;
11+
}
12+
13+
private TrieNode root;
14+
15+
public Problem_3_Design_Add_And_Search_Words_Data_Structure() {
16+
root = new TrieNode();
17+
}
18+
19+
public void addWord(String word) {
20+
TrieNode node = root;
21+
for (char c : word.toCharArray()) {
22+
if (node.children[c - 'a'] == null) {
23+
node.children[c - 'a'] = new TrieNode();
24+
}
25+
node = node.children[c - 'a'];
26+
}
27+
node.isEnd = true;
28+
}
29+
30+
public boolean search(String word) {
31+
return searchInNode(word, root);
32+
}
33+
34+
private boolean searchInNode(String word, TrieNode node) {
35+
for (int i = 0; i < word.length(); i++) {
36+
char ch = word.charAt(i);
37+
if (ch == '.') {
38+
for (TrieNode child : node.children) {
39+
if (child != null && searchInNode(word.substring(i + 1), child)) {
40+
return true;
41+
}
42+
}
43+
return false;
44+
} else {
45+
if (node.children[ch - 'a'] == null) return false;
46+
node = node.children[ch - 'a'];
47+
}
48+
}
49+
return node.isEnd;
50+
}
51+
52+
}

0 commit comments

Comments
 (0)