Skip to content

Commit c41dec1

Browse files
committed
week6 solution add
1 parent f611f28 commit c41dec1

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
m : word length
3+
n : Trie node count
4+
addWord
5+
Time Complexity: O(m)
6+
7+
search
8+
Time Complexity: O(n)
9+
10+
Space Complexity: O(26 × N × M)
11+
12+
Trie + Dfs
13+
*/
14+
15+
class WordDictionary {
16+
class TrieNode {
17+
TrieNode[] children;
18+
boolean isEnd;
19+
20+
public TrieNode() {
21+
children = new TrieNode[26];
22+
isEnd = false;
23+
}
24+
}
25+
26+
private TrieNode root;
27+
28+
public WordDictionary() {
29+
root = new TrieNode();
30+
}
31+
32+
public void addWord(String word) {
33+
TrieNode current = root;
34+
35+
for (char str : word.toCharArray()) {
36+
int idx = str - 'a';
37+
if (current.children[idx] == null) {
38+
current.children[idx] = new TrieNode();
39+
}
40+
current = current.children[idx];
41+
}
42+
current.isEnd = true;
43+
}
44+
45+
public boolean search(String word) {
46+
return dfsSearch(word, 0, root);
47+
}
48+
49+
private boolean dfsSearch(String word, int idx, TrieNode node) {
50+
if (idx == word.length()) {
51+
return node.isEnd;
52+
}
53+
54+
char c = word.charAt(idx);
55+
if (c == '.') {
56+
for (int i = 0 ; i < 26; i++) {
57+
if (node.children[i] != null) {
58+
if (dfsSearch(word, idx + 1, node.children[i])) {
59+
return true;
60+
}
61+
}
62+
}
63+
return false;
64+
} else {
65+
int charIdx = c - 'a';
66+
if (node.children[charIdx] == null) {
67+
return false;
68+
}
69+
return dfsSearch(word, idx + 1, node.children[charIdx]);
70+
}
71+
}
72+
}
73+
74+
/**
75+
* Your WordDictionary object will be instantiated and called as such:
76+
* WordDictionary obj = new WordDictionary();
77+
* obj.addWord(word);
78+
* boolean param_2 = obj.search(word);
79+
*/
80+

0 commit comments

Comments
 (0)