Welcome to Subscribe On Youtube

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;
        }
    }
    
  • // OJ: https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/
    // Time: O(MNW)
    // Space: O(1)
    class Solution {
    public:
        string findLongestWord(string s, vector<string>& A) {
            string ans;
            auto valid = [](string &a, string &b) {
                int i = 0, j = 0, M = a.size(), N = b.size();
                if (M > N) return false;
                for (; i < M; ++i, ++j) {
                    while (j < N && b[j] != a[i]) ++j;
                    if (j == N) return false;
                }
                return true;
            };
            for (auto &w : A) {
                if (w.size() >= ans.size() && valid(w, s) && (w.size() > ans.size() || w < ans)) ans = w; 
            }
            return ans;
        }
    };
    
  • class Solution:
        def findLongestWord(self, s: str, dictionary: List[str]) -> str:
            def check(a, b):
                m, n = len(a), len(b)
                i = j = 0
                while i < m and j < n:
                    if a[i] == b[j]:
                        j += 1
                    i += 1
                return j == n
    
            ans = ''
            for a in dictionary:
                if check(s, a) and (len(ans) < len(a) or (len(ans) == len(a) and ans > a)):
                    ans = a
            return ans
    
    ############
    
    import collections
    
    
    class Solution(object):
      def findLongestWord(self, s, d):
        """
        :type s: str
        :type d: List[str]
        :rtype: str
        """
        d.sort(key=lambda x: (-len(x), x))
    
        def isSubseq(word, s):
          i = 0
          for c in s:
            if c == word[i]:
              i += 1
            if i == len(word):
              return True
          return False
    
        for word in d:
          if isSubseq(word, s):
            return word
        return ""
    
    

All Problems

All Solutions