【LeetCode】Longest Word in Dictionary through Deleting 解题报告
阅读原文时间:2022年05月20日阅读:1

【LeetCode】Longest Word in Dictionary through Deleting 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/#/description

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

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output:
"apple"

Input:
s = "abpcplea", d = ["a","b","c"]

Output:
"a"

题目意思是要找出给出的输入字符串去除某些字符后能拼接成的在字典中的最长字典字符串。
如果按照题目给的意思,通过删除字符来判断剩下的字符串是否在字典里无疑是个非常繁重的工作。这个题应该反过来想:对于字典中的每个字典单词串,判断能否由输入字符串中的某些字符元素组成。方法分为两步:1.对字典字符串排序;2.查找到能最优先被输入字符串匹配的字典字符串。
题目中对结果有以下要求:返回最长或长度一样时返回字母表中最前的。那么可以对字典中的字符串按照这两个要求排序:长度降序、长度相同时字母表升序。这样遍历字典字符串列表,第一个能被输入字符串去掉某些字符表示出的字典字符串即为所求。
如何判断字典字符串能被输入字符串去除某些元素后表示出来?方法是对输入字符串的每个字符从左到右遍历,如果输入字符串的某位和字典字符串的第i位相同,那么字典字符串的指针i++指向下一位字符,再判断输入字符串此后是否存在和字典字符串当前位相同的字符,以此类推。
循环结束的i是字典字符串和输入字符串匹配的字符个数,如果i等于字典字符串的长度说明已经输入字符串能通过去掉若干字符的方式表示出字典字符串,循环结束,返回此字典字符串。

public static String findLongestWord(String s, List<String> d) {
    Collections.sort(d, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return (o1.length() != o2.length()) ?
                (o2.length() - o1.length()) : o1.compareTo(o2);
        }
    });
    for (String dictWord : d) {
        int i = 0;
        for (char c : s.toCharArray()) {
            if (i < dictWord.length() && c == dictWord.charAt(i)) {
                i++;
            }
        }
        if (i == dictWord.length()) {
            return dictWord;
        }
    }
    return "";

2017 年 4 月 7 日