|
| 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