Skip to content

Commit f3c457c

Browse files
committed
Updated Design Add and Search Words Data Structure
1 parent 9a1d239 commit f3c457c

File tree

1 file changed

+43
-44
lines changed

1 file changed

+43
-44
lines changed

Medium/Design Add and Search Words Data Structure.java

Lines changed: 43 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,53 @@
11
class WordDictionary {
2-
3-
private Node root;
4-
5-
public WordDictionary() {
6-
this.root = new Node();
7-
}
8-
9-
public void addWord(String word) {
10-
Node curr = root;
11-
for (char c : word.toCharArray()) {
12-
if (curr.children[c - 'a'] == null) {
13-
curr.children[c - 'a'] = new Node();
14-
}
15-
curr = curr.children[c - 'a'];
2+
3+
private final TrieNode root;
4+
5+
public WordDictionary() {
6+
this.root = new TrieNode();
167
}
17-
curr.isWord = true;
18-
}
19-
20-
public boolean search(String word) {
21-
Node curr = root;
22-
return searchHelper(word, 0, curr);
23-
}
24-
25-
private boolean searchHelper(String word, int idx, Node curr) {
26-
if (idx == word.length()) {
27-
return curr.isWord;
8+
9+
public void addWord(String word) {
10+
TrieNode curr = root;
11+
for (char c : word.toCharArray()) {
12+
if (!curr.children.containsKey(c)) {
13+
curr.children.put(c, new TrieNode());
14+
}
15+
curr = curr.children.get(c);
16+
}
17+
curr.isWord = true;
2818
}
29-
if (word.charAt(idx) != '.' && curr.children[word.charAt(idx) - 'a'] == null) {
30-
return false;
19+
20+
public boolean search(String word) {
21+
return searchHelper(word, 0, root);
3122
}
32-
if (word.charAt(idx) == '.') {
33-
for (Node child : curr.children) {
34-
if (child != null && searchHelper(word, idx + 1, child)) {
35-
return true;
23+
24+
private boolean searchHelper(String word, int idx, TrieNode node) {
25+
if (idx == word.length()) {
26+
return node.isWord;
3627
}
37-
}
38-
return false;
28+
if (node.children.containsKey(word.charAt(idx))) {
29+
return searchHelper(word, idx + 1, node.children.get(word.charAt(idx)));
30+
}
31+
if (word.charAt(idx) == '.') {
32+
for (TrieNode child : node.children.values()) {
33+
if (searchHelper(word, idx + 1, child)) {
34+
return true;
35+
}
36+
}
37+
}
38+
return false;
3939
}
40-
return searchHelper(word, idx + 1, curr.children[word.charAt(idx) - 'a']);
41-
}
42-
43-
private static class Node {
44-
Node[] children;
45-
boolean isWord;
46-
47-
public Node() {
48-
this.children = new Node[26];
49-
this.isWord = false;
40+
41+
42+
static class TrieNode {
43+
private final Map<Character, TrieNode> children;
44+
private boolean isWord;
45+
46+
public TrieNode() {
47+
this.children = new HashMap<>();
48+
this.isWord = false;
49+
}
5050
}
51-
}
5251
}
5352

5453
/**

0 commit comments

Comments
 (0)