Categories:

Tags:



Problem

Given a string licensePlate and an array of strings words, find the shortest completing word in words.

A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.

For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".

Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.

Constraints

  • 1 <= licensePlate.length <= 7
  • licensePlate contains digits, letters (uppercase or lowercase), or space ' '.
  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 15
  • words[i] consists of lower case English letters.

Solution

The problem Shortest Completing Word can be solved by iterating the given array and checking if each word satisfies the problem description.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    string shortestCompletingWord(string licensePlate, vector<string> &words)
    {
        int hashmap[26] = {};
        for (char &ch : licensePlate)
            if (isalpha(ch))
                hashmap[tolower(ch) - 'a'] += 1;

        string ret(16, ' ');
        for (string &word : words)
        {
            int letters[26] = {};
            for (char &ch : word)
                letters[ch - 'a'] += 1;

            bool check = true;
            for (int i = 0; i < 26; i++)
                if (hashmap[i] > letters[i])
                {
                    check = false;
                    break;
                }

            if (check && word.length() < ret.length())
                ret = word;
        }

        return ret;
    }
};