|
| 1 | +class Node: |
| 2 | + def __init__(self, s: str): |
| 3 | + self.s: str = s |
| 4 | + self.isLast: bool = False |
| 5 | + self.childs: dict[str, Node] = {} |
| 6 | + |
| 7 | + def addChild(self, s: str): |
| 8 | + if self.getChild(s) is not None: |
| 9 | + return |
| 10 | + |
| 11 | + node = Node(s) |
| 12 | + self.childs[s] = node |
| 13 | + |
| 14 | + def getChild(self, s: str) -> Node | None: |
| 15 | + if s not in self.childs: |
| 16 | + return None |
| 17 | + |
| 18 | + return self.childs[s] |
| 19 | + |
| 20 | + def setIsLast(self, isLast: bool): |
| 21 | + self.isLast = isLast |
| 22 | + |
| 23 | + def getIsLast(self) -> bool: |
| 24 | + return self.isLast |
| 25 | + |
| 26 | + |
| 27 | +class Trie: |
| 28 | + root: Node |
| 29 | + |
| 30 | + def __init__(self): |
| 31 | + self.root = Node("") |
| 32 | + |
| 33 | + def insert(self, word: str) -> None: |
| 34 | + node = self.root |
| 35 | + for i in range(len(word)): |
| 36 | + ch = word[i] |
| 37 | + if node.getChild(ch) is None: |
| 38 | + node.addChild(ch) |
| 39 | + |
| 40 | + node = node.getChild(ch) |
| 41 | + if i == len(word) - 1: |
| 42 | + node.setIsLast(True) |
| 43 | + |
| 44 | + def findNode(self, word) -> Node | None: |
| 45 | + node = self.root |
| 46 | + for ch in word: |
| 47 | + node = node.getChild(ch) |
| 48 | + if node is None: |
| 49 | + return None |
| 50 | + |
| 51 | + return node |
| 52 | + |
| 53 | + def search(self, word: str) -> bool: |
| 54 | + node = self.findNode(word) |
| 55 | + if node is None or not node.getIsLast(): |
| 56 | + return False |
| 57 | + |
| 58 | + return True |
| 59 | + |
| 60 | + def startsWith(self, prefix: str) -> bool: |
| 61 | + return self.findNode(prefix) is not None |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +# Your Trie object will be instantiated and called as such: |
| 66 | +# obj = Trie() |
| 67 | +# obj.insert(word) |
| 68 | +# param_2 = obj.search(word) |
| 69 | +# param_3 = obj.startsWith(prefix) |
0 commit comments