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:
1
Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
2
3
Output: "steps"
4
5
Explanation:
6
The smallest length word that contains the letters "S", "P", "S", and "T".
7
Note that the answer is not "step", because the letter "s" must occur in the word twice.
8
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.
Copied!
Example 2:
1
Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
2
3
Output: "pest"
4
5
Explanation:
6
There are 3 smallest length words that contains the letters "s".
7
We return the one that occurred first.
Copied!
Note:
  1. 1.
    licensePlatewill be a string with length in range[1, 7].
  2. 2.
    licensePlatewill contain digits, spaces, or letters (uppercase or lowercase).
  3. 3.
    wordswill have a length in the range[10, 1000].
  4. 4.
    Everywords[i]will consist of lowercase letters, and have length in range[1, 15].

2. Implementation

(1) Hash Table
1
class Solution {
2
public String shortestCompletingWord(String licensePlate, String[] words) {
3
int[] map = new int[26];
4
5
for (char c : licensePlate.toCharArray()) {
6
if (Character.isLetter(c)) {
7
++map[Character.toLowerCase(c) - 'a'];
8
}
9
}
10
11
String res = "";
12
int minLen = Integer.MAX_VALUE;
13
14
for (String word : words) {
15
if (word.length() >= minLen) continue;
16
if (!match(word, map)) continue;
17
minLen = word.length();
18
res = word;
19
}
20
return res;
21
}
22
23
public boolean match(String word, int[] map) {
24
int[] wordMap = new int[26];
25
for (char c : word.toCharArray()) {
26
++wordMap[c - 'a'];
27
}
28
29
for (int i = 0; i < 26; i++) {
30
if (map[i] != 0 && wordMap[i] < map[i]) {
31
return false;
32
}
33
}
34
return true;
35
}
36
}
Copied!

3. Time & Space Complexity

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