|
| 1 | +""" |
| 2 | +TrieNode: ν κΈμλ₯Ό λ΄λ λ
Έλ |
| 3 | +- children: μμλ
Έλλ€ μ μ₯νλ λμ
λ리 |
| 4 | +- end: ν΄λΉ λ
Έλμμ λ¨μ΄κ° λλλμ§ μ¬λΆ |
| 5 | +""" |
| 6 | +class TrieNode: |
| 7 | + # Trie λ
Έλ μ΄κΈ°ν |
| 8 | + def __init__(self): |
| 9 | + self.children = {} # μμ λ
Έλ μ μ₯ |
| 10 | + self.end = False # λ¨μ΄μ λμΈμ§ νμ |
| 11 | + |
| 12 | +""" |
| 13 | +Trie(νΈλΌμ΄)ꡬ쑰, DFS, μ¬κ· |
| 14 | +- addWord : λ¨μ΄λ₯Ό Trieμ μ½μ
|
| 15 | +- search : λ¨μ΄κ° Trieμ μ‘΄μ¬νλμ§ κ²μ |
| 16 | +""" |
| 17 | +class WordDictionary: |
| 18 | + |
| 19 | + # Trie μλ£κ΅¬μ‘° μ΄κΈ°ν(λ£¨νΈ λ
Έλ μμ±) |
| 20 | + def __init__(self): |
| 21 | + # Trieμ μμ(λΉ λ£¨νΈ λ
Έλ μμ±) |
| 22 | + self.root = TrieNode() |
| 23 | + |
| 24 | + def addWord(self, word: str) -> None: |
| 25 | + node = self.root # λ¨μ΄ μ½μ
μ μμ μμΉ = λ£¨νΈ λ
Έλ |
| 26 | + |
| 27 | + # λ¨μ΄μ κΈμ νλνλλ₯Ό Trieμ μ½μ
|
| 28 | + for i in word: |
| 29 | + # κΈμκ° μμ λ
Έλμ μμΌλ©΄ μλ‘μ΄ λ
Έλ μμ±ν΄μ λ»μ΄κ°κΈ° |
| 30 | + if i not in node.children: |
| 31 | + node.children[i] = TrieNode() |
| 32 | + |
| 33 | + node = node.children[i] # λ€μ κΈμ(λ
Έλ)λ‘ μ΄λ |
| 34 | + |
| 35 | + node.end = True # λ¨μ΄ μ½μ
μλ£, νμ¬ λ
Έλμμ λ¨μ΄μ λ νμ(True) |
| 36 | + |
| 37 | + |
| 38 | + def search(self, word: str) -> bool: |
| 39 | + |
| 40 | + def dfs(node,i): |
| 41 | + # λ¨μ΄λ₯Ό λ€ λκ³ λ§μ§λ§ λ
Έλκ° λ¨μ΄μ λμ΄λ©΄ node.endλ True |
| 42 | + if i == len(word): |
| 43 | + return node.end |
| 44 | + |
| 45 | + if word[i] == ".": |
| 46 | + # "." μΌ κ²½μ° λͺ¨λ μμ λ
Έλ λμμΌλ‘ μ¬κ· νμ |
| 47 | + for j in node.children.values(): |
| 48 | + if dfs(j, i+1): |
| 49 | + return True |
| 50 | + else: |
| 51 | + # "."μ΄ μλ κ²½μ° μμλ
Έλμ μλμ§ νμΈ. |
| 52 | + # μμΌλ©΄ λ€μ κΈμ νμ, μμΌλ©΄ False λ¦¬ν΄ |
| 53 | + if word[i] in node.children: |
| 54 | + return dfs(node.children[word[i]], i+1) |
| 55 | + else: |
| 56 | + return False |
| 57 | + |
| 58 | + # μΌμΉνλ λ¨μ΄κ° μλ κ²½μ°μ λλΉν μμΈ μ²λ¦¬ |
| 59 | + return False |
| 60 | + |
| 61 | + # DFSμμ(λ£¨νΈ λ
ΈλλΆν° νμ) |
| 62 | + return dfs(self.root, 0) |
| 63 | + |
| 64 | +# Your WordDictionary object will be instantiated and called as such: |
| 65 | +# obj = WordDictionary() |
| 66 | +# obj.addWord(word) |
| 67 | +# param_2 = obj.search(word) |
0 commit comments