玩命加载中 . . .

696-计数二进制子串


LeetCode 696. Count Binary Substrings

LeetCode-696

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
如果不同,就记录为preLencurLen变为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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录