1002. 查找常用字符
知识点:数组、模拟
时间:2020年10月14日
题目链接:https://leetcode-cn.com/problems/find-common-characters/
题目
给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
示例1
输入:
[“bella”,“label”,“roller”]
输出:
[“e”,“l”,“l”]
示例 2:
输入:
[“cool”,“lock”,“cook”]
输出:
[“c”,“o”]
提示:
- 1 <= A.length <= 100
- 1 <= A[i].length <= 100
- A[i][j] 是小写字母
思路
- 一个长度为26的数组a 统计每个string的字符的频率
- 另一个长度为26的数组b 和之前的取min(a,b)
- 得到每个字符出现的次数
代码
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
vector<int> dic(26,0);
vector<int> total(26,__INT_MAX__);
vector<string> ans;
int n = A.size();
for(int i=0;i<n;i++){
fill(dic.begin(), dic.end(), 0);
for(int j=0;j<A[i].size();j++){
dic[A[i][j]-'a'] ++;
}
for(int j=0;j<26;j++)
total[j] = min(total[j],dic[j]);
}
for(int i=0;i<26;i++){
for(int j=0;j<total[i];j++)
ans.emplace_back(1,i+'a');
}
return ans;
}
};
int main()
{
vector<string> A;
A.push_back("bella");
A.push_back("label");
A.push_back("roller");
Solution s;
vector<string> ans = s.commonChars(A);
for(string x: ans)
cout<<x<<endl;
return 0;
}
今天也是爱zz的一天哦!