696. Count Binary Substrings
Description
Given a binary string s, return the number of non-empty substrings that have 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 the number of times they occur.
Example 1:
Input: s = "00110011" Output: 6 Explanation: There are 6 substrings that have 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.
Example 2:
Input: s = "10101" Output: 4 Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
Constraints:
1 <= s.length <= 105s[i]is either'0'or'1'.
Solutions
Solution 1: Iteration and Counting
Thinking
Count substrings made of a run of \(0\)s next to a run of \(1\)s of equal length. Checking every substring is quadratic.
Split into runs. Adjacent runs contribute \(\min(\textit{pre},\textit{cur})\) valid substrings. One pass over the runs is enough.
We can iterate through the string \(s\), using a variable \(\textit{pre}\) to record the count of the previous consecutive characters, and another variable \(\textit{cur}\) to record the count of the current consecutive characters. The number of valid substrings ending with the current character is \(\min(\textit{pre}, \textit{cur})\). We accumulate \(\min(\textit{pre}, \textit{cur})\) to the answer, assign the value of \(\textit{cur}\) to \(\textit{pre}\), and continue iterating through string \(s\) until the end.
The time complexity is \(O(n)\), where \(n\) is the length of string \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |