748. Shortest Completing Word

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. licensePlate will be a string with length in range [1, 7] .
  2. licensePlate will contain digits, spaces, or letters (uppercase or lowercase).
  3. words will have a length in the range [10, 1000] .
  4. Every words[i] will consist of lowercase letters, and have length in range [1, 15] .
class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        if (licensePlate == null) return "";
        licensePlate = licensePlate.trim().toLowerCase().replaceAll("\\s+", "");

        int[] sourceHash = convert(licensePlate);

        Arrays.sort(words, (a, b) -> (a.length() - b.length()));

        for (String word : words){
            int[] targetHash = convert(word);

            if (cover(sourceHash, targetHash)) return word;
        }

        return "";
    }

    private int[] convert(String str){
        int[] hash = new int[26];

        for (char c : str.toCharArray()){
            if (c < 'a' || c > 'z') continue;
            hash[c - 'a']++;
        }

        return hash;
    }

    private boolean cover(int[] source, int[] target){
        for (int i = 0; i < 26; i++){
            target[i] -= source[i];
        }

        for (int i = 0; i < 26; i++){
            if (target[i] < 0) return false;
        }

        return true;
    }
}

results for ""

    No results matching ""