|
| 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(νΈλΌ): TreeκΈ°λ°μ μλ£κ΅¬μ‘°(Treeμλ£κ΅¬μ‘°μ€νλ), λ¬Έμμ΄ κ²μμ μν νΉμν Tree μλ£κ΅¬μ‘° |
| 14 | +- insert: μ£Όμ΄μ§ word μ½μ
|
| 15 | +- search: μ£Όμ΄μ§ wordκ° Trieμ μλμ§ κ²μ |
| 16 | +- startwith: μ£Όμ΄μ§ prefixλ‘ μμνλ λ¨μ΄κ° μλμ§ νμΈ |
| 17 | +""" |
| 18 | +class Trie: |
| 19 | + # Trie μλ£κ΅¬μ‘° μ΄κΈ°ν(λ£¨νΈ λ
Έλ μμ±) |
| 20 | + def __init__(self): |
| 21 | + # Trieμ μμ(λΉ λ£¨νΈ λ
Έλ μμ±) |
| 22 | + self.root = TrieNode() |
| 23 | + |
| 24 | + def insert(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 | + def search(self, word: str) -> bool: |
| 38 | + node = self.root |
| 39 | + |
| 40 | + for i in word: |
| 41 | + # κΈμκ° μμλ
Έλμ μ‘΄μ¬νμ§ μμΌλ©΄ False λ¦¬ν΄ |
| 42 | + if i not in node.children: |
| 43 | + return False |
| 44 | + |
| 45 | + node = node.children[i] # λ€μ κΈμ(λ
Έλ)λ‘ μ΄λ |
| 46 | + |
| 47 | + # λ¨μ΄λ₯Ό λ€ λκ³ λ§μ§λ§ λ
Έλκ° λ¨μ΄μ λμ΄λ©΄ node.endλ True |
| 48 | + return node.end |
| 49 | + |
| 50 | + def startsWith(self, prefix: str) -> bool: |
| 51 | + node = self.root |
| 52 | + |
| 53 | + for i in prefix: |
| 54 | + # κΈμκ° μμλ
Έλμ μ‘΄μ¬νμ§ μμΌλ©΄ False λ¦¬ν΄ |
| 55 | + if i not in node.children: |
| 56 | + return False |
| 57 | + |
| 58 | + node = node.children[i] # λ€μ κΈμ(λ
Έλ)λ‘ μ΄λ |
| 59 | + |
| 60 | + return True |
| 61 | + |
| 62 | + |
| 63 | +# Your Trie object will be instantiated and called as such: |
| 64 | +# obj = Trie() |
| 65 | +# obj.insert(word) |
| 66 | +# param_2 = obj.search(word) |
| 67 | +# param_3 = obj.startsWith(prefix) |
0 commit comments