题意:
思路:
题目有几个关键点:
- 不区分大小写
- 补全词优先选最短的
- 同样短的选最靠前的
预处理出字符串
l
i
c
e
n
s
e
P
l
a
t
e
licensePlate
licensePlate中每个字母出现的次数(不区分大小写)
然后遍历给出的补全词集合,对于每个补全词统计每个字母出现的次数,看是否符合题目的要求,再选择最靠前的最短的作为答案。
代码:
class Solution {
public:
string shortestCompletingWord(string licensePlate, vector<string>& words) {
int a[27],b[27];
memset(a,0,sizeof a);
for(int i=0;licensePlate[i];i++){
char t=licensePlate[i];
if(t>='A'&&t<='Z') a[t-'A']++;
else if(t>='a'&&t<='z') a[t-'a']++;
}
string ans="9999999999999999999999999999999999999999999999999999999";
for(string s:words){
memset(b,0,sizeof b);
for(int i=0;s[i];i++) b[s[i]-'a']++;
bool flag=1;
for(int j=0;j<26;j++)
if(a[j]!=0&&a[j]>b[j]){
flag=0;break;
}
if(flag){
if(ans.size()>s.size())
ans=s;
}
}
return ans;
}
};