#K88712. Counting Single-Letter Substrings
Counting Single-Letter Substrings
Counting Single-Letter Substrings
Given a string s
, count the total number of substrings that contain at most one distinct letter. A substring is a contiguous sequence of characters within the string.
The idea is to group consecutive identical characters and then count the substrings within each group using the formula:
\(\frac{n(n+1)}{2}\)
where \(n\) is the length of a group of identical characters.
For example, given the string "aaabb":
- The group "aaa" has \(n=3\) and contributes \(\frac{3*4}{2} = 6\) substrings.
- The group "bb" has \(n=2\) and contributes \(\frac{2*3}{2} = 3\) substrings.
The total is 6 + 3 = 9
.
inputFormat
The input consists of a single line containing the string s
(which may include only lowercase letters).
Note: the string s
can be empty, in which case the output should be 0
.
outputFormat
Output a single integer representing the total number of substrings of s
that contain at most one distinct letter.
aaabb
9