当前位置:网站首页>Force buckle 1002 Find common characters

Force buckle 1002 Find common characters

2022-07-07 11:08:00 Exy-

 

 

class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector<string> result;
        if (A.size() == 0) return result;
        int hash[26] = {0}; //  It is used to count the minimum frequency of characters in all strings 
        for (int i = 0; i < A[0].size(); i++) { //  Give... The first string hash initialization 
            hash[A[0][i] - 'a']++;
        }

        int hashOtherStr[26] = {0}; //  Count the frequency of characters except the first string 
        for (int i = 1; i < A.size(); i++) {
            memset(hashOtherStr, 0, 26 * sizeof(int));
            for (int j = 0; j < A[i].size(); j++) {
                hashOtherStr[A[i][j] - 'a']++;
            }
            //  to update hash, Guarantee hash Li statistics 26 The minimum number of times a character appears in all strings 
            for (int k = 0; k < 26; k++) {
                hash[k] = min(hash[k], hashOtherStr[k]);
            }
        }
        //  take hash Count the number of characters , Into output form 
        for (int i = 0; i < 26; i++) {
            while (hash[i] != 0) { //  Notice that this is while, Multiple duplicate characters 
                string s(1, i + 'a'); // char -> string
                result.push_back(s);
                hash[i]--;
            }
        }

        return result;
    }
};

 

原网站

版权声明
本文为[Exy-]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130620440806.html