Skip to content

Commit d60f811

Browse files
committed
feat: [Week 06-3] solve design-add-and-search-words-data-structure
1 parent 41046a9 commit d60f811

File tree

1 file changed

+112
-0
lines changed
  • design-add-and-search-words-data-structure

1 file changed

+112
-0
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
"""
2+
풀이를 보고 공부했습니다.
3+
4+
Solution:
5+
set을 이용,
6+
1) addWord 에선 add
7+
2) search 에선 .을 포함한 모든 글자가 동일한 단어가 있는지 확인
8+
9+
search
10+
Time: O(n * w)
11+
Space: O(1)
12+
"""
13+
14+
15+
class WordDictionary:
16+
17+
def __init__(self):
18+
self.root = set()
19+
20+
def addWord(self, word: str) -> None:
21+
self.root.add(word)
22+
23+
def search(self, word: str) -> bool:
24+
for candidate in self.root:
25+
if len(candidate) != len(word):
26+
continue
27+
if all(w == c or w == "." for w, c in zip(word, candidate)):
28+
return True
29+
return False
30+
31+
32+
"""
33+
풀이를 보고 공부했습니다.
34+
35+
Solution: Trie - 달레의 코드
36+
"""
37+
38+
39+
class WordDictionary:
40+
41+
def __init__(self):
42+
self.root = {"$": True}
43+
44+
def addWord(self, word: str) -> None:
45+
node = self.root
46+
for ch in word:
47+
if ch not in node:
48+
node[ch] = {"$": False}
49+
node = node[ch]
50+
node["$"] = True
51+
52+
def search(self, word: str) -> bool:
53+
def dfs(node, idx):
54+
if idx == len(word):
55+
return node["$"]
56+
57+
ch = word[idx]
58+
if ch in node:
59+
return dfs(node[ch], idx + 1)
60+
if ch == ".":
61+
if any(dfs(node[k], idx + 1) for k in node if k != "$"):
62+
return True
63+
return False
64+
65+
return dfs(self.root, 0)
66+
67+
68+
"""
69+
풀이를 보고 공부했습니다.
70+
71+
Solution: Trie with TrieNode - NeetCode
72+
"""
73+
74+
75+
class TrieNode:
76+
def __init__(self):
77+
self.children = {} # a: TrieNode
78+
self.word = False
79+
80+
81+
class WordDictionary:
82+
83+
def __init__(self):
84+
self.root = TrieNode()
85+
86+
def addWord(self, word: str) -> None:
87+
cur = self.root
88+
89+
for c in word:
90+
if c not in cur.children:
91+
cur.children[c] = TrieNode()
92+
cur = cur.children[c]
93+
cur.word = True
94+
95+
def search(self, word: str) -> bool:
96+
def dfs(j, root):
97+
cur = root
98+
for i in range(j, len(word)):
99+
c = word[i]
100+
101+
if c == ".":
102+
for child in cur.children.values():
103+
if dfs(i + 1, child):
104+
return True
105+
return False
106+
else:
107+
if c not in cur.children:
108+
return False
109+
cur = cur.children[c]
110+
return cur.word
111+
112+
return dfs(0, self.root)

0 commit comments

Comments
 (0)