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 <iostream>
2#include <string>
3using namespace std;
4
5int countBinarySubstrings(string s) {
6 int prev = 0, curr = 1, count = 0;
7 for (size_t i = 1; i < s.size(); ++i) {
8 if (s[i] == s[i - 1]) {
9 ++curr;
10 } else {
11 count += min(prev, curr);
12 prev = curr;
13 curr = 1;
14 }
15 }
16 return count + min(prev, curr);
17}
18
19int main() {
20 string s = "00110011";
21 cout << countBinarySubstrings(s) << endl;
22 return 0;
23}
The C++ solution functions similarly to the C solution, utilizing a single pass to compare current and previous character groups. It uses the min()
function to add the smaller of two consecutive group counts, ensuring we count substrings where numbers of '0's and '1's are equal.
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.
1class Solution:
2 def countBinarySubstrings(self, s: str) -> int:
3 groups = []
4 count = 0
5 i = 0
6 n = len(s)
7 while i < n:
8 ch = s[i]
9 count_ch = 0
10 while i < n and s[i] == ch:
11 i += 1
12 count_ch += 1
13 groups.append(count_ch)
14
15 for j in range(1, len(groups)):
16 count += min(groups[j - 1], groups[j])
17 return count
18
19if __name__ == '__main__':
20 sol = Solution()
21 print(sol.countBinarySubstrings('00110011'))
This Python implementation uses a similar method by first creating a list to store length of consecutive groups of similar digits, and then adds up the smaller counts of each consecutive pair in the list.