给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
vector<string> ans;
//如果输入为空,直接返回空结果
if(words.size()==0){
return ans;
}
//初始化数组为0,保存每个字母出现的次数
int hash[26]={0};
//遍历首个单词,存储每个字母出现的次数
for(int i=0;i<words[0].size();i++){
hash[words[0][i]-'a']++;
}
//遍历除第一个单词后的所有单词
for(int i=1;i<words.size();i++){
//定义其他数组,存储其他单词中字母出现的次数,初始化为0
int hashother[26]={0};
//遍历每个单词中的每个字母,存储出现的次数
for(int j=0;j<words[i].size();j++){
hashother[words[i][j]-'a']++;
}
//更新hash数组,将两个数组中出现次数少的保存下来
for(int k=0;k<26;k++){
hash[k]=min(hash[k],hashother[k]);
}
}
//遍历数组
for(int i=0;i<26;i++){
//如果对应的次数不为0
while(hash[i]!=0){
//创建长度为1的字符串s接收对应字母
string s(1,i+'a');
ans.push_back(s);
hash[i]--;
}
}
return ans;
}
};
8万+

被折叠的 条评论
为什么被折叠?



