524

给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。

示例 1:

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

示例 2:

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

解法

  • Python
class Solution:
    def findLongestWord(self, s: str, d: List[str]) -> str:
        def isSubsequence(s,d):
            indexs,indexd = 0,0
            while indexs<len(s) and indexd<len(d):
                if d[indexd] == s[indexs]:
                    indexd += 1
                indexs += 1
            if indexd == len(d):
                return True
            return False
        maxlen,maxstr = 0,''
        for i in d:
            if isSubsequence(s,i):
                if len(i) > maxlen:
                    maxlen = len(i)
                    maxstr = i
                elif len(i) == maxlen and i < maxstr:
                    maxstr = i
        return maxstr