当前位置:网站首页>【LeetCode】676. 实现一个魔法字典
【LeetCode】676. 实现一个魔法字典
2022-07-13 18:03:00 【pass night】
题目
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary()初始化对象void buildDict(String[] dictionary)使用字符串数组dictionary设定该数据结构,dictionary中的字符串互不相同bool search(String searchWord)给定一个字符串searchWord,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回true;否则,返回false。
示例:
输入
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
输出
[null, null, false, true, false, false]
解释
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // 返回 False
magicDictionary.search("hhllo"); // 将第二个 'h' 替换为 'e' 可以匹配 "hello" ,所以返回 True
magicDictionary.search("hell"); // 返回 False
magicDictionary.search("leetcoded"); // 返回 False
提示:
1 <= dictionary.length <= 1001 <= dictionary[i].length <= 100dictionary[i]仅由小写英文字母组成dictionary中的所有字符串 互不相同1 <= searchWord.length <= 100searchWord仅由小写英文字母组成buildDict仅在search之前调用一次- 最多调用
100次search
思路
- 将所有的变化情况都存储在集合当中
- 因为需要有一次变化才能匹配,所有在讲变化后的词添加到字典之前还需要判断是否与原单词相同;若相同则不添加
代码
class MagicDictionary:
def __init__(self):
self.dic = set()
def buildDict(self, dictionary: List[str]) -> None:
for word in dictionary:
for i,c in enumerate(word):
for replace in "abcdefghijklmnopqrstuvwxyz":
newWord = list(word)
newWord[i] = replace
newWord = "".join(newWord)
if newWord != word: self.dic.add(newWord)
def search(self, searchWord: str) -> bool:
return searchWord in self.dic
复杂度
设单词数为nn,平均长度为ll,字符集为\SigmaΣ
时间复杂度:
buildDict: O ( n l ∣ Σ ∣ ) O(nl|\Sigma|) O(nl∣Σ∣)
search: O ( 1 ) O(1) O(1)
空间复杂度: O ( n l ∣ Σ ∣ ) O(nl|\Sigma|) O(nl∣Σ∣)
边栏推荐
猜你喜欢

Implementation of binarysearchtree (BST) class template for binary search tree

5、 Experimental report on setting up Microsoft cluster service (MSCs) environment

Related use of unityc intermediate grammar

SAP DUMP CALLBACK_ REJECTED_ BY_ WHITELIST - SE51, RSSCREENPAINTER

MySQL - data page

单向链表实现队列和栈

HeadFirst 状态模式 源码

Unity3d monobehavior base class

联想词匹配-总结

Headfirst state mode source code
随机推荐
Get started with promise
2021-11-7bugku做题记录25——POST
For the approval of SQL changes, I set DBA approval. Why can't DBA see the list
Unity3d~ tank AI (small exercise)
unity3d-Transform组件
Shut up that thing
程序员日常技巧
5、 Experimental report on setting up Microsoft cluster service (MSCs) environment
Mid year summary - rotten
Hardware course design: sensor device of multi-function player based on stm32
Men should be "strong", not "soft", "weak" and "empty"
SAP Logon 无法正常启动
ipdb调试常用的命令
[learning progress on June 4]
Unity3d monobehavior base class
搜索二维矩阵 II
[learning records on June 2]
JVM目录
Flink On Yarn HA模式搭建问题
Implementation of dynamic array vector class template