Leetcode每日一题:1002.find-common-characters(查找常用字符串)

在这里插入图片描述
思路:可用暴力法,找出最短字符串short_string,然后对里的每个字符c,都在A里面搜索字符c的数量,数量最小值就是c在所有字符串中出现的次数;也可用计数法,即求每个字符串之间字符数量的交集;

暴力法:
在这里插入图片描述

class Solution {
public:
    vector<string> commonChars(vector<string> &A)
    {
        vector<string> res;
        //先找出最短的字符串
        string short_string = "";
        int short_size = A[0].size();
        int short_index = 0;
        int len = A.size();
        for (int i = 0; i < len; i++)
        {
            if (A[i].size() < short_size)
            {
                short_size = A[i].size();
                short_index = i;
            }
        }

        short_string = A[short_index];
        len = short_string.size();
        sort(short_string.begin(), short_string.end());

        for (int i = 0; i < len;)
        {
            char c = short_string[i];
            int min_count = len;
            for (string s : A)
            {
                int count = 0;
                for (char x : s)
                {
                    if (x == c)
                    {
                        count++;
                    }
                }
                if (count < min_count)
                {
                    min_count = count;
                }
            }
            while (min_count)
            {
                string temp = "";
                temp.push_back(c);
                res.push_back(temp);
                min_count--;
            }
            while (short_string[++i] == c)
            {
            }
        }

        return res;
    }
};

计数法:
在这里插入图片描述

class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector<int> minfreq(26, INT_MAX);
        vector<int> freq(26);
        for (const string& word: A) {
            fill(freq.begin(), freq.end(), 0);
            for (char ch: word) {
                ++freq[ch - 'a'];
            }
            for (int i = 0; i < 26; ++i) {
                minfreq[i] = min(minfreq[i], freq[i]);
            }
        }

        vector<string> ans;
        for (int i = 0; i < 26; ++i) {
            for (int j = 0; j < minfreq[i]; ++j) {
                ans.emplace_back(1, i + 'a');
            }
        }
        return ans;
    }
};
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页