124. Equal Blocks

A binary string s is made of the characters 0 and 1. Call a substring an equal block if it consists of some number of 0 characters followed directly by the same number of 1 characters, or of some number of 1 characters followed directly by the same number of 0 characters. For example 0011 and 10 are equal blocks, while 0101 is not.

Return how many equal blocks s contains. Substrings with the same text at different positions are counted separately. The intended solution scans the string once.

Example 1

Input:
s = "000111"
Output:
3
Explanation:

The equal blocks are 01, 0011 and 000111, so there are three.

Example 2

Input:
s = "0110"
Output:
2
Explanation:

The equal blocks are 01 and 10; the whole string 0110 is not an equal block.

Constraints

1 ≤ s.length ≤ 105

s contains only the characters 0 and 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…