给你一个字符串数组 words ,请你找出所有在 words 的每个字符串中都出现的共用字符(包括重复字符),并以数组形式返回。你可以按 任意顺序 返回答案。
示例 1:
**输入:**words = [“bella”,”label”,”roller”]
输出:[“e”,”l”,”l”]
示例 2:
**输入:**words = [“cool”,”lock”,”cook”]
输出:[“c”,”o”]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] 由小写英文字母组成
使用哈希表统计每个字符串中字母出现的最小次数。遍历哈希表,如果不为零则持续添加到答案中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| class Solution {
public:
vector<string> commonChars(vector<string>& words) {
int hash[26] = {0};
vector<string> ans;
for(int i=0;i<words[0].size();i++)
{
hash[words[0][i] - 'a']++;
}
int hash_other_words[26] = {0};
for(int i=1;i<words.size();i++)
{
memset(hash_other_words,0,26 * sizeof(int));
for(int j=0;j<words[i].size();j++)
{
hash_other_words[words[i][j] - 'a']++;
}
for(int k=0;k<26;k++)
{
hash[k] = min(hash[k],hash_other_words[k]);
}
}
for(int i =0;i<26;i++)
{
while(hash[i] != 0)
{
string s(1,i+'a');
ans.push_back(s);
hash[i]--;
}
}
return ans;
}
};
|