每日一题 676. 实现一个魔法字典

简介: 每日一题 676. 实现一个魔法字典

题目:

设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。

实现 MagicDictionary 类:

# 676 实现一个魔法字典
from typing import List


class MagicDictionary:
    # 初始化对象
    def __init__(self):
        pass
    # 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
    def buildDict(self, dictionary: List[str]) -> None:
        pass
    # 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。
    def search(self, searchWord: str) -> bool:
        pass

解:

没有看完题目就开始写了,下面这个版本写得很差,但是可以通过。

我用了集合表示拥有的单词,实际上用列表就可以。因为题目保证了初始化列表中不会有重复的单词。

另一个地方就是search()方法,写得非常纯真。直接判断长度,长度相同则遍历单词,判断是否有且仅有一个位置的字母不同。

# 676 实现一个魔法字典
from typing import List


class MagicDictionary:

    def __init__(self):
        self.d = set()

    def buildDict(self, dictionary: List[str]) -> None:
        for word in dictionary:
            self.d.add(word)

    def search(self, searchWord: str) -> bool:
        for word in self.d:
            if  len(word) != len(searchWord):
                continue
            for index in range(len(searchWord)):
                if word[0:index] == searchWord[0:index] and word[index]!= searchWord[index] \
                        and word[index+1:] == searchWord[index+1:]:
                    return True
        return False

参考官方题解后,做了下面的修改:

  1. 用列表保存单词
  2. search()方法使用了zip同时迭代两个单词,比较单词中不同的字母数量。如果刚好有一个字母不同,则返回True
# 676 实现一个魔法字典
from typing import List


class MagicDictionary:

    def __init__(self):
        self.words = list()

    def buildDict(self, dictionary: List[str]) -> None:
        self.words = dictionary

    def search(self, searchWord: str) -> bool:
        for word in self.words:
            if len(word) != len(searchWord):
                continue
            diff = 0
            for a,b in zip(word,searchWord):
                if a != b:
                    diff += 1
                if diff > 2:
                    break
            if diff == 1:
                return  True
        return False


来源:力扣(LeetCode)

链接:https://leetcode.cn/problems/implement-magic-dictionary

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

相关文章
|
1月前
|
存储 索引 Python
【python学习】列表、元组、字典、集合,秋招是不是得到处面试
【python学习】列表、元组、字典、集合,秋招是不是得到处面试
|
1月前
leetcode-676:实现一个魔法字典
leetcode-676:实现一个魔法字典
35 0
|
算法
leetcode-每日一题648. 单词替换(哈希)
将字符串数组中的所有字符串存入哈希表中,遍历sentence中的所有单词,从短到长遍历单词前缀,对比哈希表中的单词是否存在,存在则替换。
57 0
leetcode-每日一题648. 单词替换(哈希)
【牛客】字符集合
【牛客】字符集合
65 0
【牛客】字符集合
LeetCode每日一题——676. 实现一个魔法字典
设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
65 0
LeetCode每日一题——791. 自定义字符串排序
给定两个字符串 order 和 s 。order 的所有单词都是 唯一 的,并且以前按照一些自定义的顺序排序。
75 0
|
Java C++
每日一题——349. 两个数组的交集
每日一题——349. 两个数组的交集
93 0