LeetCode算法题解 1002-查找常用字符

题目描述

题解

我就不解释题目了,直接说思路,首先开一个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;
    }
};
发布了197 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41708792/article/details/104336632