[leetcode]748. Shortest Completing Word
Analysis
想把拖鞋塞到某男生嘴里!!!—— [生气气]
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.
其实就是个字符串匹配的问题,然后我做的时候忘记licensePlate里面还有非字母(数字,空格等),所以搞了很久,心态爆炸!
Implement
class Solution {
public:
string shortestCompletingWord(string licensePlate, vector<string>& words) {
unordered_map<char, int> mymap;
int num = 0;
for(char s:licensePlate){
if(s>='A' && s<='Z'){
mymap[s+32]++;
num++;
}
else if(s>='a' && s<='z'){
mymap[s]++;
num++;
}
}
string res = "";
for(string word:words){
int tmp = num;
unordered_map<char, int> tmpmap = mymap;
for(char c:word){
tmpmap[c]--;
if(tmpmap[c]>=0)
tmp--;
}
if(tmp==0 && (res.size()==0 || res.size()>word.size()))
res = word;
}
return res;
}
};