Skip to content

Commit 3ee9846

Browse files
committed
solve design add and search words data sturcture
1 parent a91fa79 commit 3ee9846

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class WordDictionary {
2+
private static class TrieNode {
3+
boolean isEnd;
4+
Map<Character, TrieNode> children;
5+
6+
TrieNode() {
7+
this.isEnd = false;
8+
this.children = new HashMap<>();
9+
}
10+
}
11+
12+
private final TrieNode root;
13+
14+
public WordDictionary() {
15+
root = new TrieNode();
16+
}
17+
18+
public void addWord(String word) {
19+
TrieNode node = root;
20+
for (char ch : word.toCharArray()) {
21+
node.children.putIfAbsent(ch, new TrieNode());
22+
node = node.children.get(ch);
23+
}
24+
node.isEnd = true;
25+
}
26+
27+
public boolean search(String word) {
28+
return dfs(root, word, 0);
29+
}
30+
31+
private boolean dfs(TrieNode node, String word, int index) {
32+
if (index == word.length()) {
33+
return node.isEnd;
34+
}
35+
36+
char ch = word.charAt(index);
37+
if (ch == '.') {
38+
for (TrieNode child : node.children.values()) {
39+
if (dfs(child, word, index + 1)) {
40+
return true;
41+
}
42+
}
43+
return false;
44+
}
45+
46+
TrieNode next = node.children.get(ch);
47+
if (next == null) {
48+
return false;
49+
}
50+
51+
return dfs(next, word, index + 1);
52+
}
53+
}
54+

0 commit comments

Comments
 (0)