| 8 | self.is_end = False |
| 9 | |
| 10 | class Trie: |
| 11 | def __init__(self): |
| 12 | self.root = TrieNode() |
| 13 | |
| 14 | """ |
| 15 | Inserts the string word into the trie. |
| 16 | """ |
| 17 | def insert(self, word: str) -> None: |
| 18 | curr = self.root |
| 19 | for c in word: |
| 20 | if c not in curr.children: |
| 21 | curr.children[c] = TrieNode() |
| 22 | curr = curr.children[c] |
| 23 | curr.is_end = True |
| 24 | |
| 25 | """ |
| 26 | Returns true if the string word is in the trie (i.e., was inserted before). |
| 27 | Otherwise, returns false. |
| 28 | """ |
| 29 | def search(self, word: str) -> bool: |
| 30 | curr = self.root |
| 31 | for c in word: |
| 32 | if c not in curr.children: |
| 33 | return False |
| 34 | curr = curr.children[c] |
| 35 | return curr.is_end |
| 36 | |
| 37 | """ |
| 38 | Returns true if there is a previously inserted string word that has the prefix prefix. |
| 39 | Otherwise, returns false. |
| 40 | """ |
| 41 | def starts_with(self, prefix: str) -> bool: |
| 42 | curr = self.root |
| 43 | for c in prefix: |
| 44 | if c not in curr.children: |
| 45 | return False |
| 46 | curr = curr.children[c] |
| 47 | return True |