栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode 524. Longest Word in Dictionary through Deleting 通过删除字母匹配到字典里最长单词

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode 524. Longest Word in Dictionary through Deleting 通过删除字母匹配到字典里最长单词

一、题目大意

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

给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:

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

示例 2:

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

提示:

  • 1 <= s.length <= 1000
  • 1 <= dictionary.length <= 1000
  • 1 <= dictionary[i].length <= 1000
  • s 和 dictionary[i] 仅由小写英文字母组成
二、解题思路

题意:1、字典中单词的每个字母都在字符串中按顺序出现 2、找出长度最长且字母序最小
思路:1、实现判断一个单词中的所有字符按顺序出现在另一个字符串中 2、多个相同长度的字符串取字母序最小的串

三、解题方法 3.1 Java实现
public class Solution {
    public String findLongestWord(String s, List dictionary) {
        List res = new ArrayList<>();
        int maxLen = 0;
        for (String tmp : dictionary) {
            if (isSubstring(s, tmp)) {
                if (tmp.length() > maxLen) {
                    maxLen = tmp.length();
                    res.clear();
                    res.add(tmp);
                } else if (tmp.length() == maxLen) {
                    res.add(tmp);
                }
            }
        }
        return getMin(res);
    }
    
    private boolean isSubstring(String str, String subStr) {
        int i = str.length() - 1;
        int j = subStr.length() - 1;
        while (i >= 0 && j >= 0) {
            if (str.charAt(i) == subStr.charAt(j)) {
                j--;
            }
            i--;
        }
        return j == -1;
    }

    private String getMin(List list) {
        if (list == null || list.size() == 0) {
            return "";
        }
        String minStr = list.get(0);
        for (String tmp : list) {
            if (minStr.compareTo(tmp) > 0) {
                minStr = tmp;
            }
        }
        return minStr;
    }
}
四、总结小记
  • 2022/5/20 把解题思路理清,一切就顺理成章了
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/921864.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号