给你一个字符串数组 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++){//定义其他数组,存储其他单词中字母出现的次数,初始化为0int 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++){//如果对应的次数不为0while(hash[i]!=0){//创建长度为1的字符串s接收对应字母string s(1,i+'a');ans.push_back(s);hash[i]--;}}return ans;}
};