题解:
我就不解释题目了,直接说思路,首先开一个map1记录A[0]的字母情况,然后从A[1]遍历到最后一个字符串,每次都用map2记录下字符串的字母情况,和map1做交集,遇到相同的值,取较小的出现次数,得到map3,map3赋值给map1,最后得到的map3就是所有字符串map的交集,然后把结果记录到res数组即可。
附上别人一个评论:
代码:
class Solution {
public:
vector<string> commonChars(vector<string>& A) {
vector <string> res;
int len = A.size();
map <char,int> mp1;
for(int i = 0; i < (int)A[0].length(); i++)
{
mp1[A[0][i]]++;
}
for(int i = 1; i < len; i++)
{
map <char,int> mp2;
for(int j = 0; j < (int)A[i].length(); j++)
{
mp2[A[i][j]]++;
}
map <char,int> mp3;// mp1和mp2的交集
for(auto it1 = mp1.begin(); it1 != mp1.end(); it1++)
{
for(auto it2 = mp2.begin(); it2 != mp2.end(); it2++)
{
if(it1->first == it2->first)
{
mp3[it1->first] = min(it1->second,it2->second);
break;
}
}
}
mp1 = mp3;
}
for(auto it = mp1.begin(); it != mp1.end(); it++)
{
for(int i = 1; i <= it->second; i++)
{
/** 要注意map是<char,int>,这里转换成数组的元素要从char —> string,下面是模板
char c;
string str;
stringstream stream;
stream << c;
str = stream.str();
*/
string str;
stringstream stream;
stream << it->first;
str = stream.str();
res.push_back(str);
//cout << it->first << " ";
}
}
return res;
}
};