Master and String

3.9

21 votes
Medium
Problem

Angry Master ji was fed up with Bhuavn so he gave him a problem and said that he will allow him to sit in his class only if he solves this problem. He gave him a string S which is made up of only 3 characters A,B and C. He asked him to count the number of substrings of S, which have an equal number of 'A', 'B' and 'C'. Help Bhuvan to solve this problem.

Input:

The first line of the input contains an ABC-string S.

Output:

Print a single integer, denoting the number of substrings of S, which have an equal number of 'A', 'B' and 'C'.

Constraints:

1 ≤ |S| ≤ 1000000

where |S| denotes the length of the given ABC-string.

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

In the example:

S[2..4] = "BAC" S[4..6] = "CAB" So, 2 possible substrings.

Editor Image

?