程式語言 - LeetCode - C++ - 1358. Number of Substrings Containing All Three Characters



題目:


解答:

class Solution {
public:
    int numberOfSubstrings(string s) {
        int n = s.size();
        int l = 0;
        int ans = 0;
        int cnt[3] = { 0 };

        for (int r = 0; r < n; ++r) {
            cnt[s[r] - 'a'] += 1;

            while (cnt[0] > 0 && cnt[1] > 0 && cnt[2] > 0) {
                cnt[s[l] - 'a'] -= 1;
                l += 1;
            }

            ans += l;
        }

        return ans;
    }
};