​LeetCode刷题实战524:通过删除字母匹配到字典里最长单词

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 通过删除字母匹配到字典里最长单词,我们先来看题面:

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

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string

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

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

示例                         

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

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

解题

思路:通过删除字符串 s 中的一个字符能得到字符串 t,可以认为 t 是 s 的子序列,我们可以使用双指针来判断一个字符串是否为另一个字符串的子序列,也可以使用String类的indexOf方法来验证是否是子序列。

class Solution {
    public String findLongestWord(String s, List<String> d) {
        String max= ""; // 将最长单词初始化为空,没有匹配到的情况下可以直接返回
        for (String word: d) {
            if (word.length()<max.length()) //长度小于最长单词直接跳过
                continue;
            if (word.length()==max.length() && max.compareTo(word)<0) //长度相等,但字典顺序大的也跳过
                continue;
            if (isSubstring(s, word)) //剩下符合条件的单词,若匹配上则更新最长单词
                max= word;
        }
        return max;
    }
    
    /** 匹配长字符串和单词,若单词为长字符串的子序列(即长字符串可通过删除字符变为该单词),则返回true */
    private boolean isSubstring(String str, String word) {
        int len_1= str.length();
        int len_2= word.length();
        int p=0; //单词中用于匹配的字符位置
        for (int i=0; i<len_1; i++) {
            if(str.charAt(i)==word.charAt(p)) {
                if(p==len_2-1) //字符位置已匹配到单词尾,则单词是子序列
                    return true;
                p++; //长字符串和单词中字符相等,则更新单词中下个字符位置
            }
        }
        return false; //单词没有匹配上,不是子序列
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-520题汇总,希望对你有点帮助!

LeetCode刷题实战521:最长特殊序列 Ⅰ

LeetCode刷题实战522:最长特殊序列 II

LeetCode刷题实战523:连续的子数组和

ff983801ec46346460946484aeff2068.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值