FastPrepFastPrep
Problem Brief

Count Binary Substrings

OA

A binary string is a string consisting only of 0s and 1s. A substring is a contiguous group of characters within a string.

Given a binary string, find the number of substrings that contain an equal number of 0s and 1s and all the 0s and 1s are grouped together. Note that duplicate substrings are also counted in the answer. For example, '0011' has two overlapping substrings that meet the criteria: '0011' and '01'.

Function Description

Complete the function getSubstringCount in the editor.

getSubstringCount has the following parameter(s):

  1. s: String: a binary string

Returns

int: the number of substrings that meet the criteria

1Example 1

Input
s = "011001"
Output
4
Explanation
The substrings "01", "10", "1100", and "01" have equal numbers of 0s and 1s with all 0s and 1s grouped consecutively. Hence, the answer is 4. Note that the substring "0110" has an equal number of 0s and 1s but is not counted because not all 0s and 1s are grouped together.

Constraints

Limits and guarantees your solution can rely on.

  • 1 ≤ length of s ≤ 10^5
  • The string s consists of 0s and 1s only.
public int getSubstringCount(String s) {
  // write your code here
}
Input

s

"011001"

Output

4

Sign in to submit your solution.