Formatted question description: https://leetcode.ca/all/524.html

524. Longest Word in Dictionary through Deleting

Level

Medium

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.

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.

Solution

Maintain a longest word, which is initially an empty string. Loop over the dictionary. For each word in the dictionary, check whether it is a subsequence of the given string. If so, compare the word with the longest word. If the word has a length greater than the current longest word, or the word has a length equal to the current longest word and the word is lexicographically smaller than the current longest word, then update the longest word using the current word. Finally, return the longest word.

class Solution {
    public String findLongestWord(String s, List<String> d) {
        String longestWord = "";
        for (String word : d) {
            if (isSubsequence(word, s)) {
                if (word.length() > longestWord.length() || word.length() == longestWord.length() && word.compareTo(longestWord) < 0)
                    longestWord = word;
            }
        }
        return longestWord;
    }

    public boolean isSubsequence(String word, String str) {
        int length1 = word.length(), length2 = str.length();
        int index1 = 0, index2 = 0;
        while (index1 < length1 && index2 < length2) {
            char c1 = word.charAt(index1), c2 = str.charAt(index2);
            if (c1 == c2)
                index1++;
            index2++;
        }
        return index1 == length1;
    }
}

All Problems

All Solutions