Skip to content

Commit abc923a

Browse files
committed
add design add and search words data structure solution
1 parent 6fc81e6 commit abc923a

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* WordDictionary
6+
* WordDictionary() - ๊ฐ์ฒด ์ดˆ๊ธฐํ™”
7+
* void addWord(word) - ์ž๋ฃŒ ๊ตฌ์กฐ์— word ์ถ”๊ฐ€
8+
* boolean search(word) - ์ž๋ฃŒ ๊ตฌ์กฐ์— word ์žˆ์œผ๋ฉด true ์•„๋‹ˆ๋ฉด false ๋ฐ˜ํ™˜
9+
- '.'๋Š” ์™€์ผ๋“œ์นด๋“œ๋กœ ํ™œ์šฉ ๊ฐ€๋Šฅ
10+
*/
11+
class WordDictionary {
12+
13+
private Node root;
14+
15+
public WordDictionary() {
16+
root = new Node();
17+
}
18+
19+
public void addWord(String word) {
20+
Node current = root;
21+
for (char c : word.toCharArray()) {
22+
if (!current.nodeCharacters.containsKey(c)) {
23+
current.nodeCharacters.put(c, new Node());
24+
}
25+
current = current.nodeCharacters.get(c);
26+
}
27+
current.isEnd = true;
28+
}
29+
30+
public boolean search(String word) {
31+
return searchInNode(word, 0, root);
32+
}
33+
34+
private boolean searchInNode(String word, int idx, Node node) {
35+
36+
if (node == null) {
37+
return false;
38+
}
39+
40+
if (idx == word.length()) {
41+
return node.isEnd;
42+
}
43+
44+
char c = word.charAt(idx);
45+
// ์™€์ผ๋“œ์นด๋“œ๋Š” Node์— ์žˆ๋Š” ์ „์ฒด ๊ฐ’ ๋‹ค ํƒ์ƒ‰
46+
if (c == '.') {
47+
for (Node child : node.nodeCharacters.values()) {
48+
if (searchInNode(word, idx + 1, child)) {
49+
return true;
50+
}
51+
}
52+
return false;
53+
} else {
54+
Node current = node.nodeCharacters.get(c);
55+
return searchInNode(word, idx + 1, current);
56+
}
57+
}
58+
59+
static class Node {
60+
61+
boolean isEnd;
62+
63+
Map<Character, Node> nodeCharacters;
64+
65+
Node() {
66+
nodeCharacters = new HashMap<>();
67+
isEnd = false;
68+
}
69+
70+
}
71+
}
72+
73+
/**
74+
* Your WordDictionary object will be instantiated and called as such:
75+
* WordDictionary obj = new WordDictionary();
76+
* obj.addWord(word);
77+
* boolean param_2 = obj.search(word);
78+
*/
79+

0 commit comments

Comments
ย (0)