749 Shortest Completing Word

1. Question

Find the minimum length word from a given dictionarywords, which has all the letters from the stringlicensePlate. Such a word is said tocompletethe given stringlicensePlate

Here, for letters we ignore case. For example,"P"on thelicensePlatestill matches"p"on the word.

It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.

The license plate might have the same letter occurring multiple times. For example, given alicensePlateof"PP", the word"pair"does not complete thelicensePlate, but the word"supper"does.

Example 1:

Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]

Output: "steps"

Explanation:
The smallest length word that contains the letters "S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.

Example 2:

Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]

Output: "pest"

Explanation:
There are 3 smallest length words that contains the letters "s".
We return the one that occurred first.

Note:

  1. licensePlatewill be a string with length in range[1, 7].

  2. licensePlatewill contain digits, spaces, or letters (uppercase or lowercase).

  3. wordswill have a length in the range[10, 1000].

  4. Everywords[i]will consist of lowercase letters, and have length in range[1, 15].

2. Implementation

(1) Hash Table

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        int[] map = new int[26];

        for (char c : licensePlate.toCharArray()) {
            if (Character.isLetter(c)) {
                ++map[Character.toLowerCase(c) - 'a'];
            }
        }

        String res = "";
        int minLen = Integer.MAX_VALUE;

        for (String word : words) {
            if (word.length() >= minLen) continue;
            if (!match(word, map)) continue;
            minLen = word.length();
            res = word;
        }
        return res;
    }

    public boolean match(String word, int[] map) {
        int[] wordMap = new int[26];
        for (char c : word.toCharArray()) {
            ++wordMap[c - 'a'];
        }

        for (int i = 0; i < 26; i++) {
            if (map[i] != 0 && wordMap[i] < map[i]) {
                return false;
            }
        }
        return true;
    }
}

3. Time & Space Complexity

(1) Hash Table: 时间复杂度O(nL), n是word的个数,L是words里的word的平均长度,空间复杂度O(1)

Last updated