Skip to content

Commit 601ed62

Browse files
design add and search words data structure solution
1 parent cc824fd commit 601ed62

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
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+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(N), N(word์˜ ๊ธธ์ด)
6+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(N)
7+
Map<Character, WordDictionary> child;
8+
boolean isEnd;
9+
10+
public WordDictionary() {
11+
child = new HashMap<>();
12+
isEnd = false;
13+
}
14+
15+
public void addWord(String word) {
16+
var node = this;
17+
for (int i = 0; i < word.length(); i++) {
18+
char c = word.charAt(i);
19+
20+
node.child.putIfAbsent(c, new WordDictionary());
21+
node = node.child.get(c);
22+
23+
if (i == word.length() - 1) {
24+
node.isEnd = true;
25+
return;
26+
}
27+
}
28+
}
29+
30+
public boolean search(String word) {
31+
return searchHelper(word, 0, this);
32+
}
33+
34+
private boolean searchHelper(String word, int index, WordDictionary node) {
35+
if (index == word.length()) {
36+
return node.isEnd;
37+
}
38+
39+
char c = word.charAt(index);
40+
// . ์ด ๋‚˜์˜ค๋ฉด ํ•ด๋‹น ๋…ธ๋“œ์˜ ์ž์‹ ๋…ธ๋“œ๋“ค์— ๋Œ€ํ•ด ๋ชจ๋‘ ์žฌ๊ท€๋ฅผ ๋Œ๋ฆฐ๋‹ค
41+
if (c == '.') {
42+
for (WordDictionary childNode : node.child.values()) {
43+
if (searchHelper(word, index + 1, childNode)) {
44+
return true;
45+
}
46+
}
47+
return false;
48+
} else {
49+
var childNode = node.child.get(c);
50+
if (childNode == null) {
51+
return false;
52+
}
53+
return searchHelper(word, index + 1, childNode);
54+
}
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)