2021.6.1-查找常用字符

题目链接:https://leetcode-cn.com/problems/find-common-characters/
题目描述:

题解:


class Solution {
public:
    vector<string> commonChars(vector<string>& words) {
        vector<string> result;
        vector<int> hash(26);
        //将第一个字符串的字符个数作为hash表的初始值
        for(char ch: words[0])
        {
            hash[ch - 'a']++;
        }
        //逐个统计剩余字符串的字符个数
        for(int i = 1; i < words.size(); i++)
        {
            vector<int> temp(26);
            for(char ch: words[i])
            {
                temp[ch - 'a']++;
            }
            //更新hash中的值,记录2个字符串所有字母出现的最小频率字母
            for(int j = 0; j < 26; j++)
            {
                hash[j] = min(hash[j], temp[j]);
            }
        }
        for(int i = 0; i < hash.size(); i++)
        {
            while(hash[i] != 0)
            {
                string s(1, 'a' + i);  //char转为一个string
                result.push_back(s);
                hash[i]--;
            }
            
        }
        return result;
    }
};

posted @ 2021-06-01 10:51  张宵  阅读(47)  评论(0编辑  收藏  举报