https://leetcode.com/problems/find-common-characters/
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
// set<char> s;
int cnt1[26]{INT_MAX};
memset(cnt1,1,sizeof(cnt1));
// fill(cnt1,cnt1+26,INT_MAX);
for(int i = 0 ; i< 26;i++) cout<<cnt1[i]<<endl;
vector<int> cnt(26,INT_MAX);
for(auto a:A){
int c[26]{0};
for(auto ss:a) c[ss-'a']++;
for(int i = 0 ; i < 26 ;i++) cnt[i] = min(c[i],cnt[i]);
}
// cout<<cnt[2] <<endl;
vector<string> res;
int n;
for(int i = 0;i<26;i++){
if(cnt[i]!= 0 ){
n = cnt[i];
while(n--){
res.emplace_back(string(1, i + 'a'));
}
}
}
return res;
}
};
两个小收获:
1.对于int数据的赋值,不能使用int a[26]{INT_MAX}来。
应当使用fill(a,a+26,INT_MAX);
2.从char变成string,可以使用string(1,‘a’+i);
第一个参数表示后面的char重复的次数;后面’a’+i表示a后面第i个字母。
这里相当于构造函数,只是没有名字而已,叫做临时变量。
string str1(5, 'a');
cout << str1 << endl;//aaaaa
string NoName(5, 'a');
string (5, 'a');
531

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



