676. Implement Magic Dictionary
Đề Bài
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the MagicDictionary class:
MagicDictionary()Initializes the object.void buildDict(String[] dictionary)Sets the data structure with an array of distinct stringsdictionary.bool search(String searchWord)Returnstrueif you can change exactly one character insearchWordto match any string in the data structure, otherwise returnsfalse.
Example 1:
Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Output
[null, null, false, true, false, false]
Explanation
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
Constraints:
1 <= dictionary.length <= 1001 <= dictionary[i].length <= 100dictionary[i]consists of only lower-case English letters.- All the strings in
dictionaryare distinct. 1 <= searchWord.length <= 100searchWordconsists of only lower-case English letters.buildDictwill be called only once beforesearch.- At most
100calls will be made tosearch.
Thuật Toán & Kỹ Thuật
⏱️ Thời gian
O(n²)
💾 Không gian
O(n)
Lời Giải
Python
0676-implement-magic-dictionary.py
class Node:
def __init__(self):
self.isLastWord = False
self.children = defaultdict(Node)
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
root = self.root
for char in word:
root = root.children[char]
root.isLastWord = True
def find(self, word: str) -> bool:
root = self.root
for char in word:
if char not in root.children:
return False
root = root.children[char]
return root.isLastWord
class MagicDictionary:
def __init__(self):
self.trie = Trie()
def buildDict(self, dictionary: List[str]) -> None:
for word in dictionary:
self.trie.insert(word)
def search(self, searchWord: List[str]) -> bool:
n = len(searchWord)
searchWord = list(searchWord)
for i in range(n):
for step in range(26):
if step == ord(searchWord[i]) - ord('a'):
continue
tmp = searchWord[i]
searchWord[i] = chr(step + ord('a'))
if self.trie.find(searchWord):
return True
searchWord[i] = tmp
return False
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)