LeetCode-in-Java

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:

Solution

public 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;
    }
}