forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlylaminju.py
58 lines (42 loc) Β· 1.75 KB
/
lylaminju.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
'''
* L: λ¨μ΄μ κΈΈμ΄
μκ°λ³΅μ‘λ: O(1)
- addWord(word): O(L), μ΅λ λ¨μ΄ κΈΈμ΄κ° 25λ‘ μ νλλ―λ‘ μ΄ μμ
μ μμ μκ°μ κ°κΉμ΅λλ€.
- search(word): O(L * 26^d), μ¬κΈ°μ 26μ μνλ²³ μλ¬Έμμ κ°μλ₯Ό μλ―Έν©λλ€. dλ λ¨μ΄ λ΄ '.'μ κ°μμΈλ°, 2λ‘ μ νλλ―λ‘ μμ μκ°μ κ°κΉμ΅λλ€.
곡κ°λ³΅μ‘λ:
- Trie ꡬ쑰μ μ μ₯λλ λ¬Έμμ μμ λΉλ‘ν©λλ€. λ¨μ΄μ μ΄ κΈΈμ΄λ₯Ό TλΌκ³ νλ©΄ 곡κ°λ³΅μ‘λλ O(T) μ
λλ€.
'''
class Trie:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class WordDictionary:
def __init__(self):
# Trieμ λ£¨νΈ λ
Έλ μ΄κΈ°ν
self.root = Trie()
def addWord(self, word: str) -> None:
current = self.root
for char in word:
if char not in current.children:
current.children[char] = Trie()
current = current.children[char]
current.is_end_of_word = True
def search(self, word: str) -> bool:
def dfs(node, i):
if i == len(word):
return node.is_end_of_word
char = word[i]
if char == '.':
# '.'μΈ κ²½μ° λͺ¨λ μμ λ
Έλμ λν΄ νμ
for child in node.children.values():
if dfs(child, i + 1):
return True
return False
if char not in node.children:
return False
return dfs(node.children[char], i + 1)
return dfs(self.root, 0)
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)