个人感觉这题难度不止简单,考察到的东西还是挺多的。 首先理解题意,可以将题意转化为:求字符串数组中 各字符串共同出现的字符的最小值。 分为三步做:
遍历第一个hash表将频率大于0的字符放入ans中。
代码如下:
- class Solution {
- public:
- vector
commonChars(vector& words) { - //本题可以简化为求数组中各字符串共同出现的字符的最小值
- vector
ans; - int hash[26] = {0};
- //初始化第一个字符串的字母出现频率
- for(int i=0; i
0].size(); i++) - {
- hash[words[0][i]-'a'] += 1;
- }
- int other_hash[26] = {0};
- //每个字符串都统计出频率,并和第一个字符串的频率比较,取小的那一个。
- for(int i=1; i
size(); i++) - {
- memset(other_hash , 0 , 26*(sizeof(int))); //重新初始化other_hash数组为全0
- for(int j=0; j
size(); j++) - {
- other_hash[words[i][j]-'a'] += 1;
- }
- for(int k=0; k<26; k++)
- {
- hash[k] = min(hash[k] , other_hash[k]);
- }
- }
- //遍历hash将频率大于0的字符放入ans中
- for(int i=0; i<26; i++)
- {
- string s(1 , 'a'+i);
- while(hash[i]--) ans.push_back(s);
- }
- return ans;
- }
- };
ps:有几个点注意下:
'a' 的ASCII码值决定。