Skip to content

Commit daa753f

Browse files
committed
Design Add and Search Words Data Structure
1 parent 40aff0f commit daa753f

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+
Time Complexity:
3+
- add: O(w)
4+
- search: O(26^2 * w) = O(w)
5+
Space Complexity: O(w)
6+
7+
Trie를 활용하되, '.'의 탐색이 필요한 경우에는 for문을 사용한다.
8+
9+
*/
10+
class WordDictionary {
11+
class Node {
12+
public char ch;
13+
public boolean ends;
14+
public Map<Character, Node> children;
15+
16+
Node() {
17+
this.children = new HashMap<>();
18+
}
19+
20+
Node(char ch) {
21+
this.ch = ch;
22+
this.children = new HashMap<>();
23+
}
24+
}
25+
26+
Node root;
27+
28+
public WordDictionary() {
29+
this.root = new Node();
30+
}
31+
32+
public void addWord(String word) {
33+
Node curr = this.root;
34+
35+
for (int i = 0; i < word.length(); i++) {
36+
char ch = word.charAt(i);
37+
if (!curr.children.containsKey(ch)) {
38+
curr.children.put(ch, new Node(ch));
39+
}
40+
41+
if (i == word.length() - 1) {
42+
curr.children.get(ch).ends = true;
43+
} else {
44+
curr = curr.children.get(ch);
45+
}
46+
}
47+
}
48+
49+
public boolean search(String word) {
50+
return searchChar(word, 0, this.root);
51+
}
52+
53+
private boolean searchChar(String word, int idx, Node curr) {
54+
if (curr == null) {
55+
return false;
56+
} else if (idx == word.length()) {
57+
return curr.ends;
58+
}
59+
60+
char ch = word.charAt(idx);
61+
62+
if (ch == '.') {
63+
for (Character key : curr.children.keySet()) {
64+
if (searchChar(word, idx + 1, curr.children.get(key))) {
65+
return true;
66+
}
67+
}
68+
return false;
69+
} else {
70+
return searchChar(word, idx + 1, curr.children.get(ch));
71+
}
72+
}
73+
}
74+
75+
/**
76+
* Your WordDictionary object will be instantiated and called as such:
77+
* WordDictionary obj = new WordDictionary();
78+
* obj.addWord(word);
79+
* boolean param_2 = obj.search(word);
80+
*/

0 commit comments

Comments
 (0)