Given a binary string s, return the number of non-empty substrings with the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted by the number of times they occur.
Input Format
A String
Constraint
1 <= s.length <= 105
s[i] is either '0' or '1'.
Output Format
An integer value
Sample Input 0
00110011
Sample Output 0
6
Explanation 0
There are 6 substrings that have an equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Notice that some of these substrings repeat and are counted the number of times they occur. Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
import java.io.*;
import java.util.*;
public class Solution {
static int countSubstring(String S, int n){
// To store the total count of substrings
int ans = 0;
int i = 0;
// Traversing the string
while (i < n) {
// Count of consecutive 0's & 1's
int count0 = 0, count1 = 0;
// Counting subarrays of type "01"
if (S.charAt(i) == '0') {
// Count the consecutive 0's
while (i < n && S.charAt(i) == '0') {
count0++;
i++;
}
// If consecutive 0's ends then check for
// consecutive 1's
int j = i;
// Counting consecutive 1's
while (j < n && S.charAt(j) == '1') {
count1++;
j++;
}
}
// Counting subarrays of type "10"
else {
// Count consecutive 1's
while (i < n && S.charAt(i) == '1') {
count1++;
i++;
}
// If consecutive 1's ends then check for
// consecutive 0's
int j = i;
// Count consecutive 0's
while (j < n && S.charAt(j) == '0') {
count0++;
j++;
}
}
// Update the total count of substrings with
// minimum of (count0, count1)
ans += Math.min(count0, count1);
}
// Return answer
return ans;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str = sc.next();
int n=str.length();
System.out.println(countSubstring(str, n));
}
}