524. Longest Word in Dictionary through Deleting (Medium)

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 1: Two Pointers, Brute Force 105ms

Time Complexity: $$O(nk)$$, where n is the length of string s and k is the number of words in the dictionary.

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        int m = s.size();
        string res;
        for (auto& w: d) {
            int i = 0, j = 0, n = w.size();
            while (i < m && j < n) {
                if (s[i] == w[j]) ++j;
                ++i;
            }
            if (j == n) {
                if (n > res.size()) res = w;
                else if (n == res.size()) res = min(res, w);
            }
        }
        return res;
    }
};

Solution 2: Two Pointers, Sort 125ms

We sort the input dictionary by longest length and lexicography. Then, we iterate through the dictionary exactly once. In the process, the first dictionary word in the sorted dictionary which appears as a subsequence in the input string s must be the desired solution.

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        sort(d.begin(), d.end(), [](string& a, string& b) {
            if (a.size() == b.size()) return a < b;
            return a.size() > b.size();
        });

        int m = s.size();
        for (auto& w: d) {
            int i = 0, j = 0, n = w.size();
            while (i < m && j < n) {
                if (s[i] == w[j]) ++j;
                ++i;
            }
            if (j == n) return w;
        }
        return "";
    }
};

results matching ""

    No results matching ""