Skip to content

Commit 716fd2a

Browse files
author
sangbeenmoon
committed
solved design-add-and...
1 parent e60be98 commit 716fd2a

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
class WordDictionary {
5+
6+
7+
Map<Character, WordDictionary> map;
8+
boolean isEnd = false;
9+
10+
public WordDictionary() {
11+
map = new HashMap<>();
12+
}
13+
14+
public void addWord(String word) {
15+
char ch = word.charAt(0);
16+
WordDictionary node;
17+
if (map.containsKey(ch)) {
18+
node = map.get(ch);
19+
} else {
20+
node = new WordDictionary();
21+
}
22+
23+
map.put(ch, node);
24+
25+
if (word.length() == 1) {
26+
node.isEnd = true;
27+
return;
28+
}
29+
30+
node.addWord(word.substring(1));
31+
}
32+
33+
public boolean search(String word) {
34+
if (word.length() == 0) {
35+
return isEnd;
36+
}
37+
38+
char ch = word.charAt(0);
39+
WordDictionary node;
40+
41+
if (ch == '.') {
42+
for (Map.Entry<Character, WordDictionary> entry : map.entrySet()) {
43+
if (entry.getValue().search(word.substring(1))){
44+
return true;
45+
}
46+
}
47+
}
48+
49+
if (map.containsKey(ch)) {
50+
node = map.get(ch);
51+
return node.search(word.substring(1));
52+
}
53+
54+
return false;
55+
}
56+
}
57+
58+
/**
59+
* Your WordDictionary object will be instantiated and called as such:
60+
* WordDictionary obj = new WordDictionary();
61+
* obj.addWord(word);
62+
* boolean param_2 = obj.search(word);
63+
*/

0 commit comments

Comments
 (0)