[Leetcode]676.Implement Magic Dictionary
链接:LeetCode676
实现一个带有buildDict, 以及 search方法的魔法字典。
对于buildDict方法,你将被给定一串不重复的单词来构建一个字典。
对于search方法,你将被给定一个单词,并且判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
示例 1:
Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False
相关标签:字典树
又是一道典型的字典树类型题。这题考察的关键点是,在给出一个word后,判定能否只将这个单词中一个字母换成另一个字母,使得新单词在字典树中。那么,我们可以通过递归判定:
- 如果这个词还没有进行更新,我们需要判断在哪个位置的字符进行更换。
- 如果这个词已经进行了更新,我们只需要判定更新后的词是否在字典树即可。
注意,当出现“hello,hallo”的组合时,查找hello,应该判定为正确。也就是说,我们在循环过程中,当该字符出现在字典树中,我们既要考察不更新的情况,也要考察更新的情况。
代码如下:
python:
import collections
class Node():
def __init__(self):
self.children = collections.defaultdict(lambda:Node())
self.isWord = False
class Trie():
def __init__(self):
self.root = Node()
def insert(self,word):
cur = self.root
for w in word:
cur = cur.children[w]
cur.isWord= True
def isWord(self,word,node):
for w in word:
if w not in node.children:return False
node = node.children[w]
return node.isWord
def search(self,word):
cur = self.root
return self.searchWithNode(word,cur)
def searchWithNode(self,word,node):
if not word:return False
for child in node.children:
if child == word[0] and self.searchWithNode(word[1:],node.children[child]):
return True
if child != word[0] and self.isWord(word[1:],node.children[child]):
return True
return False
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.tree = Trie()
def buildDict(self, dict: List[str]) -> None:
"""
Build a dictionary through a list of words
"""
for word in dict:
self.tree.insert(word)
def search(self, word: str) -> bool:
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
"""
return self.tree.search(word)
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dict)
# param_2 = obj.search(word)