LeetCode524:通过删除字母匹配到字典里最长单词(python)

2022/1/25 22:06:04

本文主要是介绍LeetCode524:通过删除字母匹配到字典里最长单词(python),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题解:

s 中每个字符和 dictionary 中每个 字符串 进行比较,记录最长的那一个,且字典序是最小的。

先排序,解决最长字符串的同时字典序最小的问题
后比较,两个指针,分别指向 s 和 dictionary 中的字符串t,挨个比较。

字符串t的指针长度跟字符串t本身长度一致,就说明 s 删除一些子串可以变成字符串t

class Solution:
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        #先将dictionary进行排序,由长到短,然后再按字母小的在前
        sorted_dictionary = sorted(dictionary,key = lambda x:[-len(x),x])

        for t in sorted_dictionary:
            i=0
            j = 0
            while i <len(t) and j<len(s):
                if t[i]==s[j]:
                    i += 1
                j += 1
                if i == len(t):
                    return t
                
        return ''



这篇关于LeetCode524:通过删除字母匹配到字典里最长单词(python)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程