524. Longest Word in Dictionary through Deleting

1. 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.

2. Example

Example 1:
Input: s = “abpcplea”, d = [“ale”,“apple”,“monkey”,“plea”]
Output: “apple”

Example 2:
Input: s = “abpcplea”, d = [“a”,“b”,“c”]
Output: “a”

3. Note

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

4. Solutions

My Accepted Solution

n = i_directionary.size()
Time complexity: O($nlog_2n$)
Space complexity: O(1)

class Solution 
{
public:
    string findLongestWord(const string &i_str, vector<string> &i_directionary) 
    {
        sort(i_directionary.begin(), i_directionary.end(), [](string left, string right)
             {
                 if(left.size() == right.size()) return left < right;
                 else return left.size() > right.size();
             }
            );
        // if we sort, when we find a valid answer, we could stop imediately
        // if we don't, we have to compare all strings to find all answers, and find the most suitable one

        for(auto str : i_directionary)
        {
            for(int i = 0, j = 0; i < i_str.size() && j < str.size(); i++)
            {
                if(i_str[i] == str[j]) j++;
                if(j == str.size()) return str;
            }
        }
        
        return string("");
    }
};
comments powered by Disqus