total
to 0 to count the number of substrings.left
and right
to 0. These pointers define the boundaries of the current segment with one distinct letter.s
using the right
pointer.right
has not reached the end of the string and s[right]
is the same as s[left]
, increment right
to extend the current segment.s[right]
is different from s[left]
, calculate the length of the current segment as right - left
, apply the arithmetic sequence sum formula to get the number of substrings for this segment, and add it to total
.left
to the current right
position to start a new segment.right
reaches the end of the string.