In this approach, we maintain two counters to track consecutive groups of 0's and 1's as we move through the string. By comparing these group counts, we can determine the number of valid equal-length substrings.
As we traverse the string, we increment the count for the current group and check if the previous group length is greater than or equal to the current group length. This indicates that we can form a valid substring.
Time Complexity: O(n) because we make a single pass through the string.
Space Complexity: O(1) since we use a constant amount of extra space.
1#include <stdio.h>
2#include <string.h>
3
4int countBinarySubstrings(char * s) {
5 int prev = 0, curr = 1, count = 0;
6 for (int i = 1; s[i] != '\0'; i++) {
7 if (s[i] == s[i - 1]) {
8 curr++;
9 } else {
10 count += (prev < curr) ? prev : curr;
11 prev = curr;
12 curr = 1;
13 }
14 }
15 return count + ((prev < curr) ? prev : curr);
16}
17
18int main() {
19 char s[] = "00110011";
20 printf("%d\n", countBinarySubstrings(s));
21 return 0;
22}
The above code uses a two-pointer technique to track the lengths of consecutive characters. It keeps track of the current and previous group lengths and increases the output count based on the lesser of the two. This ensures only valid substrings with equal '0's and '1's are counted.
This approach involves creating an array to store the lengths of consecutive 0's and 1's. By iterating through this array, we add the minimum value of each pair to a count, which represents valid substrings.
First, traverse the string to form groups, then iterate through the formed group to compute the valid substring count based on consecutive groups' minimum lengths.
Time Complexity: O(n) - The string is traversed twice, but both passes are O(n).
Space Complexity: O(n) due to the need to store group lengths.
1import java.util.ArrayList;
2import java.util.List;
3
4public class Solution {
5 public int countBinarySubstrings(String s) {
6 List<Integer> groups = new ArrayList<>();
7 int count = 0, n = s.length();
8 int i = 0;
9
10 while (i < n) {
11 char ch = s.charAt(i);
12 int c = 0;
13 while (i < n && s.charAt(i) == ch) {
14 i++;
15 c++;
16 }
17 groups.add(c);
18 }
19
20 for (int j = 1; j < groups.size(); ++j) {
21 count += Math.min(groups.get(j - 1), groups.get(j));
22 }
23 return count;
24 }
25
26 public static void main(String[] args) {
27 Solution sol = new Solution();
28 System.out.println(sol.countBinarySubstrings("00110011"));
29 }
30}
Similarly in Java, this approach first creates a list to hold counts of groups of 0's and 1's, and then sums the minimal group counts of adjacent entries.