leetcode 524. Longest Word in Dictionary through Deleting 通过删除字母匹配到字典里最长单词
阅读原文时间:2022年05月20日阅读:1

一、题目大意

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、多个相同长度的字符串取字母序最小的串

三、解题方法

public class Solution {
    public String findLongestWord(String s, List<String> dictionary) {
        List<String> 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<String> 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 把解题思路理清,一切就顺理成章了