Problem 521
Count Binary Substrings
Easy · 10 pts · String, Two Pointers
Problem
Given a binary string S, count its non-empty substrings that have the same number of 0s and 1s, where all the 0s are grouped together and all the 1s are grouped together (like 0011 or 10, but not 0101). Substrings at different positions count separately. Split S into runs of equal characters; two neighbouring runs of lengths a and b contribute min(a, b) such substrings.
Input
A single binary string S.
Output
Print the number of such substrings.
Constraints
1 <= |S| <= 100000; S contains only 0 and 1
Example input
00110011
Example output
6
Explanation
The string 00110011 has runs 00, 11, 00, 11. Each pair of neighbouring runs contributes min(2, 2) = 2 substrings (for example 0011 and 01), and there are 3 pairs, so the answer is 6.