题目描述
Implement a magic directory with buildDict, and search methods.
For the method buildDict, you’ll be given a list of non-repetitive words to build a dictionary.
For the method search, you’ll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.
Example 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
Note:
You may assume that all the inputs are consist of lowercase letters a-z.
For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.
题目要求建立一个字典,查找一个word 改变并且只改变一个字符后在字典中是否存在。
解决思路是根据字符串的大小建立索引,如果字符串的大小在索引不存在则直接返回false, 如果存在则遍历字典中和待查询字符同样大小的字符串集合,查看是否有满足改变只改变一个字符后相等的字符串。
C++ 实现
1 | class MagicDictionary { |
该实现响应时间击败Leetcode 上其他100%