|
| 1 | +class TrieNode: |
| 2 | + def __init__(self): |
| 3 | + self.children = {} |
| 4 | + self.isEnd = False |
| 5 | + |
| 6 | +class Trie: |
| 7 | + # Init Structure |
| 8 | + def __init__(self): |
| 9 | + self.root = TrieNode() |
| 10 | + |
| 11 | + # Time Complexity: O(n), n = len(word) |
| 12 | + # Space Complexity: O(n) |
| 13 | + def insert(self, word: str) -> None: |
| 14 | + current = self.root |
| 15 | + for c in word: |
| 16 | + if c not in current.children: |
| 17 | + current.children[c] = TrieNode() |
| 18 | + current = current.children[c] |
| 19 | + current.isEnd = True |
| 20 | + |
| 21 | + # Time Complexity: O(n), n = len(word) |
| 22 | + # Space Complexity: O(1) |
| 23 | + def search(self, word: str) -> bool: |
| 24 | + current = self.root |
| 25 | + for c in word: |
| 26 | + if c not in current.children: |
| 27 | + return False |
| 28 | + current = current.children[c] |
| 29 | + return current.isEnd # Check whole characters were matched |
| 30 | + |
| 31 | + # Time Complexity: O(n), n = len(prefix) |
| 32 | + # Space Complexity: O(1) |
| 33 | + def startsWith(self, prefix: str) -> bool: |
| 34 | + current = self.root |
| 35 | + for c in prefix: |
| 36 | + if c not in current.children: |
| 37 | + return False |
| 38 | + current = current.children[c] |
| 39 | + return True |
| 40 | + |
| 41 | + |
| 42 | +tc = [ |
| 43 | + ("insert", "apple", None), |
| 44 | + ("search", "apple", True), |
| 45 | + ("search", "app", False), |
| 46 | + ("startsWith", "app", True), |
| 47 | + ("insert", "app", None), |
| 48 | + ("search", "app", True), |
| 49 | + ("insert", "banana", None), |
| 50 | + ("search", "banana", True), |
| 51 | + ("search", "bananas", False), |
| 52 | + ("startsWith", "ban", True), |
| 53 | + ("startsWith", "baz", False), |
| 54 | + ("search", "", False), |
| 55 | + ("startsWith", "", True) |
| 56 | +] |
| 57 | + |
| 58 | +trie = Trie() |
| 59 | +for i, (op, value, expected) in enumerate(tc, 1): |
| 60 | + if op == "insert": |
| 61 | + result = trie.insert(value) |
| 62 | + elif op == "search": |
| 63 | + result = trie.search(value) |
| 64 | + elif op == "startsWith": |
| 65 | + result = trie.startsWith(value) |
| 66 | + else: |
| 67 | + result = None # unknown operation |
| 68 | + |
| 69 | + if result == expected: |
| 70 | + print(f"TC {i} is Passed!") |
| 71 | + else: |
| 72 | + print(f"TC {i} is Failed! - Op: {op}('{value}'), Expected: {expected}, Result: {result}") |
0 commit comments