Skip to content

Commit 2706b2a

Browse files
committed
design-add-and-search-words-data-structure solution (py, ts)
1 parent ea0e395 commit 2706b2a

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class WordDictionary:
2+
3+
def __init__(self):
4+
self.root = {"$": True}
5+
6+
7+
# TC: O(W), SC: O(W)
8+
def addWord(self, word: str) -> None:
9+
node = self.root
10+
for ch in word:
11+
if ch not in node: # 글자가 node에 없으면
12+
node[ch] = {"$": False} # 아직 끝이 아님 표시
13+
node = node[ch] # 자식 노드로 변경
14+
node["$"] = True # 단어 끝 표시
15+
16+
17+
# TC: O(26^W) => 최악의 경우 영어 알파벳 26개가 각 노드에서 다음 글자가 됨 * 글자수의 비례해서 호출 스택 깊어짐, SC: O(W)
18+
def search(self, word: str) -> bool:
19+
def dfs(node, idx):
20+
if idx == len(word):
21+
return node["$"]
22+
23+
ch = word[idx]
24+
if ch in node:
25+
return dfs(node[ch], idx + 1)
26+
if ch == ".": # 글자가 .이라면
27+
# 노드의 모든 자식 노드 호출 (어느 경로에서 글자가 일치할지 모르기 때문)
28+
if any(dfs(node[k], idx + 1) for k in node if k != '$'):
29+
return True
30+
return False
31+
32+
return dfs(self.root, 0) # 최상위 노드, 최초 idx
33+
34+
35+
# Your WordDictionary object will be instantiated and called as such:
36+
# obj = WordDictionary()
37+
# obj.addWord(word)
38+
# param_2 = obj.search(word)
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class WordDictionary {
2+
root: Record<string, any>;
3+
4+
constructor() {
5+
this.root = { $: true };
6+
}
7+
8+
addWord(word: string): void {
9+
let node = this.root;
10+
for (const ch of word) {
11+
if (!(ch in node)) {
12+
node[ch] = { $: false };
13+
}
14+
node = node[ch];
15+
}
16+
node["$"] = true;
17+
}
18+
19+
search(word: string): boolean {
20+
const dfs = (node: Record<string, any>, idx: number): boolean => {
21+
if (idx === word.length) return node["$"];
22+
23+
const ch = word[idx];
24+
if (ch === ".") {
25+
for (const key in node) {
26+
if (key !== "$" && dfs(node[key], idx + 1)) {
27+
return true;
28+
}
29+
}
30+
return false;
31+
}
32+
33+
if (ch in node) {
34+
return dfs(node[ch], idx + 1);
35+
}
36+
37+
return false;
38+
};
39+
return dfs(this.root, 0);
40+
}
41+
}
42+
43+
/**
44+
* Your WordDictionary object will be instantiated and called as such:
45+
* var obj = new WordDictionary()
46+
* obj.addWord(word)
47+
* var param_2 = obj.search(word)
48+
*/

0 commit comments

Comments
 (0)