1002. Find Common Characters

参考:https://leetcode.com/problems/find-common-characters/discuss/247573/C%2B%2B-O(n)-or-O(1)-two-vectors

地址:https://leetcode.com/problems/find-common-characters/

  1. vector初始化:vector<int> a(7,3) // 把a初始化为包含7个值为3的int
  2. char转化为string:string(1,ch)
  3. for (auto s : A)
  4. 使用min
class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector<int> cnt(26, INT_MAX);
        vector<string> res;

        for (auto s : A)
        {
            vector<int> cnt1(26, 0);
            for (auto c : s)
                cnt1[c - 'a'] ++;
            for (auto i = 0; i < 26; ++i)
                cnt[i] = min(cnt[i], cnt1[i]);
        }

        for (auto i = 0; i < 26; ++i)
            for (auto j = 0; j < cnt[i]; ++j)
                res.push_back(string(1, i + 'a'));
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/tornado549/p/10514018.html