Number of Substrings Containing All Three Characters
Description
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:
3 <= s.length <= 5 x 10^4
s
only consists of a, b or c characters.
Solution(javascript)
/** Sliding Window?
* @param {string} s
* @return {number}
*/
const numberOfSubstrings = function (s) {
let result = 0
const isValid = map => map.a >= 1 && map.b >= 1 && map.c >= 1
const map = {}
let front = 0
for (let i = 0; i < s.length; i++) {
map[s[i]] = (map[s[i]] || 0) + 1
if (isValid(map)) {
result += s.length - i
map[s[front++]] -= 1
while (isValid(map)) {
result += s.length - i
map[s[front++]] -= 1
}
}
}
return result
}