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:
licensePlatewill be a string with length in range[1, 7].
licensePlatewill contain digits, spaces, or letters (uppercase or lowercase).
wordswill have a length in the range[10, 1000].
Everywords[i]will consist of lowercase letters, and have length in range[1, 15].
2. Implementation
(1) HashTable
classSolution {publicStringshortestCompletingWord(String licensePlate,String[] words) {int[] map =newint[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 (isMatch(word, map)) { minLen =word.length(); res = word; } }return res; }publicbooleanisMatch(String word,int[] map) {int[] wordMap =newint[26];for (char c :word.toCharArray()) {++wordMap[c -'a']; }for (int i =0; i <26; i++) {if (map[i] !=0&& wordMap[i] < map[i]) {returnfalse; } }returntrue; }}