0524. Longest Word in Dictionary through Deleting (M)

Longest Word in Dictionary through Deleting (M)

题目

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.

Example 1:

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

Output: 
"apple"

Example 2:

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

Output: 
"a"

Note:

  1. All the strings in the input will only contain lower-case letters.
  2. The size of the dictionary won't exceed 1,000.
  3. The length of all the strings in the input won't exceed 1,000.

题意

给定字符串s和一个单词列表d,判断能否在s中删去若干个字符后得到d中的某一个单词,返回能得到的最长的单词。

思路

判断一个字符串s删去若干字符后能否得到字符串t,等价于判断t中所有字符是否在s中按顺序出现。遍历每一个单词,按照上述方法判断是否符合,最后选出最长的即可。


代码实现

Java

class Solution {
    public String findLongestWord(String s, List<String> d) {
        String ans = "";
        int maxLen = 0;

        for (String word : d) {
            if (isValid(s, word) && (word.length() > maxLen || word.length() == maxLen && word.compareTo(ans) < 0 )) {
                maxLen = word.length();
                ans = word;
            }
        }

        return ans;
    }

    private boolean isValid(String s, String word) {
        int i = 0, j = 0;
        while (j < word.length() && i < s.length()) {
            char a = s.charAt(i), b = word.charAt(j);
            if (a == b) {
                j++;
            }
            i++;
        }
        return j == word.length();
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/14432601.html