- 题目描述:
给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。
你可以按任意顺序返回答案。
输入:[“bella”,“label”,“roller”]
输出:[“e”,“l”,“l”]
- 解题思路
一开始直接统计所有字串相同字母的个数然后/字串个数,就得到输出相同字符的个数了,但后来发现不对劲,如果一个符串有很多相同的字母时结果就错了,例如
输入:[“abbbbbbb”,“abc”,“bcd”]
输出:[“b”]
- 其他
练习了string 和vector 的使用
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#define LL long long
using namespace std;
vector<string> commonChars(vector<string>& A) {
int t[26];
int a[26];
vector <string> res;
memset(a,0x7f,sizeof(a));
for(int i=0;i<A.size();i++){
memset(t,0,sizeof(t));
for(int j=0;j<A[i].size();j++){
t[A[i][j]-'a']++;
}
for(int _=0;_<26;_++){
if(a[_]>t[_]){
a[_]=t[_];
}
}
}
for(int x =0;x<26;x++){
for(int y=0;y<a[x];y++){
string rr = "";
rr.push_back((char)(x+'a'));
res.push_back(rr);
}
}
return res;
}
int main()
{
//["acabcddd","bcbdbcbd","baddbadb","cbdddcac","aacbcccd","ccccddda","cababaab","addcaccd"]
vector <string> a;
a.push_back("acabcddd");
a.push_back("bcbdbcbd");
a.push_back("baddbadb");
a.push_back("cbdddcac");
a.push_back("aacbcccd");
vector <string> res = commonChars(a);
for(int i=0;i<res.size();i++){
cout<<res[i]<<endl;
}
return 0;
}
本文通过一个具体的C++程序实例,展示了如何解决给定字符串数组中寻找共同字符的问题。通过对每个字符串中字符出现次数的统计,并找到这些字符在所有字符串中共同出现的最小次数,从而得出最终答案。文章深入探讨了string和vector的使用技巧,为读者提供了实际的编程经验。
151

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



