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

题目

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

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

示例

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

想法

1、先将dictionary按照 长度由长到短,字典序由小到大排序

dictionary.sort(key=lambda x:(-len(x),x))

2、双指针遍历匹配字符
3、输出最大的

实现

方法1:python

class Solution:
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        res=list()
        dictionary.sort(key=lambda x:(-len(x),x))
        for i in range(len(dictionary)):
            var=0
            k=0
            j=0
            while(k<len(s) and j<len(dictionary[i])):
                if dictionary[i][j]==s[k]:
                    k+=1
                    j+=1
                    var+=1
                else:
                    k+=1
            if var==len(dictionary[i]):
                res.append(var)
            else:
                res.append(0)
        flagv=max(res)
        for i,v in enumerate(res):
            if v==flagv:
                flag=i
                break
        if flagv==0:
            return("")
        else:
            return(dictionary[flag])

在这里插入图片描述
方法2:java

class Solution {
    public String findLongestWord(String s, List<String> dictionary) {
        String res = "";
        for (String str : dictionary) {
            // 如果dictionary的元素是s的字串
            if (isSubsequence(str, s)) {
                // 如果长度大于直接copy
                if (str.length() > res.length()) {
                    res = str;
                } else if (str.length() == res.length()) {
                    // 相等则比较字典序
                    if (str.compareTo(res) < 0) {
                        res = str;
                    }
                }
            }
        }

        return res;
    }

    public boolean isSubsequence(String s, String t) {
        if (s.length() == 0) {
            return true;
        }
        // 记录下标
        int cnt_s = 0, cnt_t = 0;
        // 逐位比较
        while (cnt_t < t.length()) {
            if (s.charAt(cnt_s) == t.charAt(cnt_t)) {
                cnt_s++;
            }
            cnt_t++;
            // s是t的字串
            if (cnt_s == s.length()) {
                return true;
            }
        }

        return false;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值