LeetCode in Kotlin

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

class Solution {
    fun numberOfSubstrings(s: String): Int {
        val counts = IntArray(3)
        var i = 0
        val n = s.length
        var result = 0
        for (j in 0 until n) {
            counts[s[j].code - 'a'.code]++
            while (counts[0] > 0 && counts[1] > 0 && counts[2] > 0) {
                counts[s[i++].code - 'a'.code]--
            }
            result += i
        }
        return result
    }
}