|
| 1 | +class TrieNode: |
| 2 | + def __init__(self): |
| 3 | + # ๋ค์ ๋ฌธ์๋ก ์ฐ๊ฒฐ๋๋ ์์ ๋
ธ๋ |
| 4 | + self.children = {} |
| 5 | + |
| 6 | + # ํ์ฌ ๋
ธ๋์์ ํ๋์ ์์ฑ๋ ๋จ์ด๊ฐ ๋๋๋์ง ํ์ |
| 7 | + self.is_end_of_word = False |
| 8 | + |
| 9 | + |
| 10 | +class Trie: |
| 11 | + def __init__(self): |
| 12 | + # ๋ชจ๋ ๋จ์ด ํ์์ด ์์๋๋ ์ต์์ ๋
ธ๋ |
| 13 | + self.root = TrieNode() |
| 14 | + |
| 15 | + def insert(self, word: str) -> None: |
| 16 | + current_node = self.root |
| 17 | + |
| 18 | + # ๋จ์ด์ ๊ฐ ๋ฌธ์๋ฅผ ๋ฐ๋ผ๊ฐ๋ฉฐ ๊ฒฝ๋ก๋ฅผ ์์ฑํ๋ค. |
| 19 | + for char in word: |
| 20 | + if char not in current_node.children: |
| 21 | + current_node.children[char] = TrieNode() |
| 22 | + |
| 23 | + current_node = current_node.children[char] |
| 24 | + |
| 25 | + # ๋ง์ง๋ง ๋
ธ๋์ ๋จ์ด์ ๋์์ ํ์ํ๋ค. |
| 26 | + current_node.is_end_of_word = True |
| 27 | + |
| 28 | + def search(self, word: str) -> bool: |
| 29 | + last_node = self._find_last_node(word) |
| 30 | + |
| 31 | + # ๊ฒฝ๋ก๊ฐ ์กด์ฌํ๊ณ , ๋ง์ง๋ง ๋
ธ๋์์ ๋จ์ด๊ฐ ๋๋์ผ ํ๋ค. |
| 32 | + return ( |
| 33 | + last_node is not None |
| 34 | + and last_node.is_end_of_word |
| 35 | + ) |
| 36 | + |
| 37 | + def startsWith(self, prefix: str) -> bool: |
| 38 | + # ์ ๋์ฌ๋ ํด๋น ๊ฒฝ๋ก๊ฐ ์กด์ฌํ๊ธฐ๋ง ํ๋ฉด ๋๋ค. |
| 39 | + return self._find_last_node(prefix) is not None |
| 40 | + |
| 41 | + def _find_last_node(self, text: str): |
| 42 | + current_node = self.root |
| 43 | + |
| 44 | + # ๋ฌธ์์ด์ ๊ฐ ๋ฌธ์๋ฅผ ๋ฐ๋ผ ๋ง์ง๋ง ๋
ธ๋๊น์ง ์ด๋ํ๋ค. |
| 45 | + for char in text: |
| 46 | + if char not in current_node.children: |
| 47 | + return None |
| 48 | + |
| 49 | + current_node = current_node.children[char] |
| 50 | + |
| 51 | + return current_node |
0 commit comments