- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/design-add-and-search-words-data-structure/description
- topics: Trie
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary
class:
WordDictionary()
Initializes the object.void addWord(word)
Addsword
to the data structure, it can be matched later.bool search(word)
Returnstrue
if there is any string in the data structure that matchesword
orfalse
otherwise.word
may contain dots'.'
where dots can be matched with any letter.
class WordDictionary(object):
def __init__(self):
self.trie = {}
def addWord(self, word):
"""
:type word: str
:rtype: None
"""
if not word:
return
pointer = self.trie
for c in word:
if not c in pointer:
pointer[c] = {}
pointer = pointer[c]
pointer["$"] = True
def search(self, word):
"""
:type word: str
:rtype: bool
"""
def search_node(word, node):
for i, ch in enumerate(word):
if ch in node:
node = node[ch]
else:
if ch == '.':
for x in node:
if x != '$' and search_node(word[i+1:], node[x]):
return True
return False
return '$' in node
return search_node(word, self.trie)