【Leetcode每日一题】524. 通过删除字母匹配到字典里最长单词

524. 通过删除字母匹配到字典里最长单词



题目

给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。

如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。


示例

示例1

输入:s = “abpcplea”, dictionary = [“ale”,“apple”,“monkey”,“plea”]
输出:“apple”

示例2

输入:s = “abpcplea”, dictionary = [“a”,“b”,“c”]
输出:“a”


关键思路

按顺序将字符串s中的每个字符与字典单词中的每个字符进行匹配,在此之前我们需要设置一个列表 index 用来维护每个单词已经被匹配到的下标。当循环结束后,根据 index 列表中的下标,选取字典中最长的字符串。


代码实现

class Solution(object):
    def findLongestWord(self, s, dictionary):
        """
        :type s: str
        :type dictionary: List[str]
        :rtype: str
        """

        index = [ [0, w] for w in dictionary ]  # to save corresponding index between s and d

        for c in s:
            for j in range(len(dictionary)):  # current character is equal to c
                if index[j][0] != len(dictionary[j]) and dictionary[j][index[j][0]] == c:
                    index[j][0] = index[j][0] + 1  # next charater

        index.sort(key=lambda x:x[0], reverse=True)
        if index[0][0] == 0:
                return ""
        for k in index:
            if k[0] == len(k[1]):
                return k[1]


if __name__ == "__main__":
    s = input()
    dictionary = input()
    obj = Solution()
    result = obj.findLongestWord(s, dictionary)
    print(result)

运行结果

apple
a

实验心得

突然意识到写条件判断的时候,是依次按照if判断句中的先后顺序进行判断。例如,当条件判断句为if A and B时,先对A进行判断,如果A为False,那么程序就不会对B进行判断。

链接

https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值