https://leetcode.com/problems/shortest-completing-word/description/
https://leetcode.com/problems/shortest-completing-word/discuss/110137/Java-Solution-using-character-Array
sort will make the runtime worse
X. https://www.cnblogs.com/grandyang/p/8407446.html
如果这道题的单词是按长度排序的话,那么上面的方法就不是很高效了,因为其会强制遍历完所有的单词。所以我们考虑给单词排序,博主这里用了TreeMap这个数据结构建立单词长度和包含所有该长度单词的数组之间的映射,其会自动按照单词长度来排序。然后还使用了一个chars数组来记录车牌中的所有字母,这样就可以方便的统计出字母总个数。我们从单词长度等于字母总个数的映射开始遍历,先检验该长度的所有单词。这里检验方法跟上面略有不同,但都大同小异,用一个bool型变量succ,初始化为true,然后建立一个字母和其出现次数的映射,先遍历单词,统计各个字母出现的次数。然后就遍历chars数组,如果chars中某个字母不在单词中,那么succ赋值为false,然后break掉。最后我们看succ,如果仍为true,直接返回当前单词word,之后的单词就不用再检验了
Find the minimum length word from a given dictionary
words
, which has all the letters from the string licensePlate
. Such a word is said to complete the given string licensePlate
Here, for letters we ignore case. For example,
"P"
on the licensePlate
still 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 a
licensePlate
of "PP"
, the word "pair"
does not complete the licensePlate
, 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:
licensePlate
will be a string with length in range[1, 7]
.licensePlate
will contain digits, spaces, or letters (uppercase or lowercase).words
will have a length in the range[10, 1000]
.- Every
words[i]
will consist of lowercase letters, and have length in range[1, 15]
.
public String shortestCompletingWord(String licensePlate, String[] words) {
String target = licensePlate.toLowerCase();
int [] charMap = new int[26];
// Construct the character map
for(int i = 0 ; i < target.length(); i++){
if(Character.isLetter(target.charAt(i))) charMap[target.charAt(i) - 'a']++;
}
int minLength = Integer.MAX_VALUE;
String result = null;
for (int i = 0; i < words.length; i++){
String word = words[i].toLowerCase();
if(matches(word, charMap) && word.length() < minLength) {
minLength = word.length();
result = words[i];
}
}
return result;
}
private boolean matches(String word, int[] charMap){
int [] targetMap = new int[26];
for(int i = 0; i < word.length(); i++){
if(Character.isLetter(word.charAt(i))) targetMap[word.charAt(i) - 'a']++;
}
for(int i = 0; i < 26; i++){
if(charMap[i]!=0 && targetMap[i]<charMap[i]) return false;
}
return true;
}
}
public String shortestCompletingWord(String licensePlate, String[] words) {
if (licensePlate == null || words == null) {
return null;
}
Map<Character, Long> freqs = getFreqs(licensePlate);
System.out.println(freqs);
String result = null;
outer: for (String word : words) {
Map<Character, Long> tmp = getFreqs(word);
if (tmp.size() < freqs.size())
continue;
for (Entry<Character, Long> entry : freqs.entrySet()) {
if (tmp.getOrDefault(entry.getKey(), 0L) < entry.getValue())
continue outer;
}
// not yet return word;
if (result == null || word.length() < result.length()) {
result = word;
}
// Local variable result defined in an enclosing scope must be final or
// effectively final
// not work
// Optional.ofNullable(result).ifPresentOrElse((t) -> {
// }, () -> {
// result = word;
// });
}
// better to use optional
return result; // don't forget this
}
private Map<Character, Long> getFreqs(String word) {
return word.chars().mapToObj(i -> (char) i).filter(ch -> (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
.map(ch -> Character.toLowerCase(ch))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
https://leetcode.com/problems/shortest-completing-word/discuss/112916/easy-javasort will make the runtime worse
public String shortestCompletingWord(String licensePlate, String[] words) {
int[] letter = new int[26];
for (char c : licensePlate.toLowerCase().toCharArray()) {
if (Character.isLetter(c)) letter[c- 'a']++;
}
Arrays.sort(words, (String a, String b) -> a.length() - b.length());
for (String word : words) {
if (helper(letter.clone(), word)) return word;
}
return "";
}
public boolean helper(int[] letter, String word) {
for (char c : word.toLowerCase().toCharArray()) {
if (Character.isLetter(c)) letter[c - 'a']--;
}
for (int l : letter) {
if (l > 0) return false;
}
return true;
}
X. https://www.cnblogs.com/grandyang/p/8407446.html
如果这道题的单词是按长度排序的话,那么上面的方法就不是很高效了,因为其会强制遍历完所有的单词。所以我们考虑给单词排序,博主这里用了TreeMap这个数据结构建立单词长度和包含所有该长度单词的数组之间的映射,其会自动按照单词长度来排序。然后还使用了一个chars数组来记录车牌中的所有字母,这样就可以方便的统计出字母总个数。我们从单词长度等于字母总个数的映射开始遍历,先检验该长度的所有单词。这里检验方法跟上面略有不同,但都大同小异,用一个bool型变量succ,初始化为true,然后建立一个字母和其出现次数的映射,先遍历单词,统计各个字母出现的次数。然后就遍历chars数组,如果chars中某个字母不在单词中,那么succ赋值为false,然后break掉。最后我们看succ,如果仍为true,直接返回当前单词word,之后的单词就不用再检验了
string shortestCompletingWord(string licensePlate, vector<string>& words) { map<int, vector<string>> m; vector<char> chars; for (string word : words) { m[word.size()].push_back(word); } for (char c : licensePlate) { if (c >= 'a' && c <= 'z') chars.push_back(c); else if (c >= 'A' && c <= 'Z') chars.push_back(c + 32); } for (auto a : m) { if (a.first < chars.size()) continue; for (string word : a.second) { bool succ = true; unordered_map<char, int> freq; for (char c : word) ++freq[c]; for (char c : chars) { if (--freq[c] < 0) {succ = false; break;} } if (succ) return word; } } return ""; }