|
| 1 | +# n: number of words | m: length of the word |
| 2 | +# TC: O(n*m) |
| 3 | +# SC: O(n*m) |
| 4 | + |
| 5 | + |
| 6 | +class TrieNode: |
| 7 | + def __init__(self): |
| 8 | + self.children = {} # Dictionary to store child TrieNodes |
| 9 | + self.is_word = False # Flag to indicate if a word ends at this node |
| 10 | + |
| 11 | + |
| 12 | +class WordDictionary: |
| 13 | + def __init__(self): |
| 14 | + # Initialize WordDictionary with a root TrieNode. |
| 15 | + self.root = TrieNode() |
| 16 | + |
| 17 | + def addWord(self, word): |
| 18 | + # Add a word to the Trie. |
| 19 | + current_node = self.root |
| 20 | + |
| 21 | + # Traverse each character in the word |
| 22 | + for character in word: |
| 23 | + # Create a new TrieNode if the character doesn't exist in children |
| 24 | + current_node = current_node.children.setdefault(character, TrieNode()) |
| 25 | + |
| 26 | + # Mark the end of the word at the last character's node |
| 27 | + current_node.is_word = True |
| 28 | + |
| 29 | + def search(self, word): |
| 30 | + |
| 31 | + def dfs(node, index): |
| 32 | + if index == len(word): |
| 33 | + # If reached end of the word, check if current node marks the end of a word |
| 34 | + return node.is_word |
| 35 | + |
| 36 | + if word[index] == ".": |
| 37 | + # Handle wildcard character '.': Try all possible children |
| 38 | + for child in node.children.values(): |
| 39 | + if dfs(child, index + 1): |
| 40 | + return True |
| 41 | + elif word[index] in node.children: |
| 42 | + # Regular character: Move to the next node |
| 43 | + return dfs(node.children[word[index]], index + 1) |
| 44 | + |
| 45 | + # If no match found, return False |
| 46 | + return False |
| 47 | + |
| 48 | + # Start DFS from the root of the Trie |
| 49 | + return dfs(self.root, 0) |
0 commit comments