LeetCode 696. Count Binary Substrings
Give 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".
method
preLen
记录之前出现的连续0或1的个数,curLen
记录当前出现的1或0的个数
如果一直与前一个字符相同,curLen
就一直加1
如果不同,就记录为preLen
,curLen
变为1
如果preLen >= curLen
,说明前面可以与后面对应,计数加1
int countBinarySubstrings(string s) {
int preLen = 0, curLen = 1;
int res = 0;
for (int i = 1; i < s.size(); ++i) {
if (s[i] == s[i - 1]) curLen++;
else {
preLen = curLen; // 记录这段有多少相同
curLen = 1; // 不同就重新置1
}
if (preLen >= curLen) res++;
}
return res;
}