class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root=TrieNode()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: void
"""
cur=self.root
for w in word:
if not w in cur.children:
cur.children[w]=TrieNode()
cur=cur.children[w]
cur.isWord=True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
cur=[self.root]
for i,w in enumerate(word):
newcur=[]
for node in cur:
for key,value in node.children.items():
if w=='.' or w==key:
if i==len(word)-1 and value.isWord:
return True
newcur.append(value)
cur=newcur
return False
python leetcode 211. Add and Search Word - Data structure design
最新推荐文章于 2022-11-01 19:14:02 发布