#676
Implement Magic Dictionary
specialist · 760 · lc medium +31 · 57.7% accepted · 1,466 likes · top 53%
Description
Build a data structure that, given a query word, can determine whether substituting exactly one of its characters produces a word in a pre-loaded collection.
Implement the MagicDictionary class:
- MagicDictionary() Constructs the object.
- void buildDict(String[] dictionary) Populates the structure with the provided array of distinct strings.
- bool search(String searchWord) Returns true if exactly one character of searchWord can be replaced to form a word in the dictionary, otherwise returns false.
Example 1:
Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Output
[null, null, false, true, false, false]
Example 2:
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
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16