1. 程式人生 > 實用技巧 >七牛雲

七牛雲

給定僅有小寫字母組成的字串陣列 A,返回列表中的每個字串中都顯示的全部字元(包括重複字元)組成的列表。例如,如果一個字元在每個字串中出現 3 次,但不是 4 次,則需要在最終答案中包含該字元 3 次。

你可以按任意順序返回答案。

示例 1:

輸入:["bella","label","roller"]
輸出:["e","l","l"]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-common-characters
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

計數

ans.emplace_back(1, 'a' + i);

表示將'a'+i 重複1次後 插入,如果是2的話,就是重複2次後插入

class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector <int> vec(26, INT_MAX);
        vector <int> tmp(26);

        for (auto s : A) {
            fill(tmp.begin(), tmp.end(), 0);
            for (auto ch : s) {
                tmp[ch - 'a']++;
            }
            for (int i = 0; i < 26; i++) {
                vec[i] = min(vec[i], tmp[i]);
            }
        }

        vector <string> ans;
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < vec[i]; j++) {
                ans.emplace_back(1, 'a' + i);
            }
        }

        return ans;

    }
};