โ† All problems

1358. Number of Substrings Containing All Three Characters

MediumOpen on LeetCodeProblem statement

Problem Statement

1358. Number of Substrings Containing All Three Characters

Medium


Given a string s consisting only of characters a, b and c.

Return the number of substrings containing at least one occurrence of all these characters a, b and c.

 

Example 1:

Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). 

Example 2:

Input: s = "aaacb"
Output: 3
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". 

Example 3:

Input: s = "abc"
Output: 1

 

Constraints:

Java โ€” sliding window

Source file
class Solution {
    public int numberOfSubstrings(String s) {
        int n = s.length(), lt = 0, rt = 0, ans = 0;
        int[] freq = new int[3];
        while (rt < n) {
            freq[s.charAt(rt) - 'a']++;
            while (valid(freq)) {
                ans += n - rt;
                freq[s.charAt(lt++) - 'a']--;
            }
            rt++;
        }
        return ans;
    }

    boolean valid(int[] freq) {
        return freq[0] > 0 && freq[1] > 0 && freq[2] > 0;
    }
}