1358. Number of Substrings Containing All Three Characters

Difficulty:
Related Topics:
Similar Questions:

Problem

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:

Solution (Java)

class Solution {
    public int numberOfSubstrings(String s) {
        int[] counts = new int[3];
        int i = 0;
        int n = s.length();
        int result = 0;
        for (int j = 0; j < n; j++) {
            counts[s.charAt(j) - 'a']++;
            while (counts[0] > 0 && counts[1] > 0 && counts[2] > 0) {
                counts[s.charAt(i++) - 'a']--;
            }
            result += i;
        }
        return result;
    }
}

Explain:

nope.

Complexity: