今日の1つの質問を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;
    }
};

おすすめ

転載: blog.csdn.net/wyll19980812/article/details/109073415