美文网首页
524. 通过删除字母匹配到字典里最长单词

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

作者: 秃头哥编程 | 来源:发表于2021-09-14 22:03 被阅读0次

2021-09-14 LeetCode每日一题

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

标签:数组、双指针、字符串、排序

题目

给你一个字符串 s 和一个字符串数组 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] 仅由小写英文字母组成

分析

返回长度最长且字典序最小的字符串。所以我们需要先给列表排个序,最好是按字典序倒序排,如果正序排的,反向遍历也是可以的。

排好序后,其实就是用字符串和目标字符串s进行比较了,这里可以使用双指针分别执行字符串和目标字符串,如果相等则一起移动,不相等移动一个。

可以优化的点,就是在比较之前,可以先判断字符串的长度是否大于等于当前符合条件的最长字符串的长度,如果小于那不用比较了,肯定不是最优解。另外如果字符串长度大于目标字符串s的长度,那么也不用比较了。

编码

class Solution {
    public String findLongestWord(String s, List<String> dictionary) {
        // 自然排序
        dictionary.sort(String.CASE_INSENSITIVE_ORDER);
        int max = 0, sLen = s.length();
        String res = "";

        // 反向遍历
        for (int i = dictionary.size() - 1; i >= 0; --i) {
            String str = dictionary.get(i);
            int len = str.length();
            if (len > sLen || len < max) {
                continue;
            }
            int left = 0, right = 0, count = 0;
            while (right < sLen && left < len) {
                if (str.charAt(left) == s.charAt(right)) {
                    left++;
                    right++;
                    count++;
                } else {
                    right++;
                }
            }

            if (count == len && count >= max) {
                max = count;
                res = str;
            }
        }

        return res;
    }
}
请添加图片描述

相关文章

网友评论

      本文标题:524. 通过删除字母匹配到字典里最长单词

      本文链接:https://www.haomeiwen.com/subject/plehgltx.html