Leetcode 748 Shortest Completing 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]
.
题意分析
给定一个licensePlate,其中有任何字符,在words中找一个word,使他包含licensePlate中的所有英文字符,大写小写看成一样的,如licensePlate中有3个a1个b,则此word中也至少有3个a1个b,找出这些word中最小且最早出现的。
解法分析
本题采用哈希表来实现,将licensePlate中的所有英文字母以及出现次数存到一个map “license”中,对word中元素进行遍历,并建立map“word”,在word中查询license中的元素以及他们出现的次数,如果全部出现且次数大于等于license中的,则符合条件,如果长度还最小,则为输出结果。在程序中我对words进行了排序,这样能从最短的元素开始遍历,注意由于输出第一个最短的满足条件的word,因此这里的排序一定是稳定的排序,用stable_sort实现。C++代码如下:
class Solution {
public:
static bool compareI(string a,string b){
return b.size()>a.size();
}
string shortestCompletingWord(string licensePlate, vector<string>& words) {
unordered_map<char,int> license;
unordered_map<char,int> word;
string res="aaaaaaaaaaaaaaaaa";
stable_sort(words.begin(),words.end(),compareI);
for(char l:licensePlate){
if(l>='a'&&l<='z')
license[l]++;
else if(l>='A'&&l<='Z'){
l+=32;
license[l]++;
}
else
continue;
}
for(string s:words){
word.clear();
for(char ss:s)
word[ss]++;
auto iter=license.begin();
for(iter=license.begin();iter!=license.end();iter++){
if(word.find((*iter).first)!=word.end()){
if(word[(*iter).first]>=(*iter).second)//>= is important
continue;
else
break;
}
else
break;
}
if(iter==license.end()){
res=(res.size()>s.size())?s:res;
}
}
return res;
}
};
由于输出第一个满足条件的word,因此res=(res.size()>s.size())?s:res中采用的是>,不然会让后面满足条件的元素赋给res。