Faaez Razeen

Design Add and Search Words Data Structure

  • 2 min read
  • Trie
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O()O()
class TrieNode: def __init__(self): self.children = {} self.end = False class WordDictionary: def __init__(self): self.root = TrieNode() def addWord(self, word: str) -> None: cur = self.root for ch in word: if ch not in cur.children: cur.children[ch] = TrieNode() cur = cur.children[ch] cur.end = True def search(self, word: str) -> bool: def dfs(root, i): cur = root for j in range(i, len(word)): ch = word[j] if ch == '.': for child in cur.children.values(): if dfs(child, j + 1): return True return False elif ch not in cur.children: return False cur = cur.children[ch] return cur.end return dfs(self.root, 0)