LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

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

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

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

示例 1:

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

示例 2:

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

提示:

数组 双指针 中等

代码

class Solution:
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        m = len(s)
        for i, word in enumerate(dictionary):
            dictionary[i] = (-len(word), word)
        dictionary.sort(key=lambda d:(d[0], d[1]))
        for n, word in dictionary:
            i, j = 0, 0 
            n = -n
            while i < m and j < n:
                if s[i] == word[j]:
                    j += 1
                i += 1
            if j == n:
                return word
        return ''