题目来源
题目描述
题目解析
根据题意,我们先统计 licensePlate 中每个字母的出现次数(忽略大小写),然后遍历 words 中的每个单词,若 2626 个字母在该单词中的出现次数均不小于在licensePlate 中的出现次数,则该单词是一个补全词。返回最短且最靠前的补全词。
class Solution {
public:
string shortestCompletingWord(string licensePlate, vector<string>& words) {
std::array<int, 26> cnt{};
for(auto ch : licensePlate){
if(isalpha(ch)){
++cnt[tolower(ch) - 'a'];
}
}
int idx = -1;
for (int i = 0; i < words.size(); ++i) {
array<int, 26> curr {};
for(auto ch : words[i]){
++curr[ch - 'a'];
}
bool ok = true;
for (int j = 0; j < 26; ++j) {
if(curr[j] < cnt[j]){
ok = false;
break;
}
}
if(ok && (idx < 0 || words[i].size() < words[idx].size())){
idx = i;
}
}
return words[idx];
}
};