LeetCode 696 Count Binary Substrings (Python)

Posted by 小明MaxMing on April 24, 2021

题目

Give a string s, count the number of non-empty (contiguous) 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.

解题思路

比较连续两段的长度,可以构成较短长度个符合要求的字符串,

代码

class Solution:
    def countBinarySubstrings(self, s: str) -> int:
        pre, cur, res = 0, 1, 0
        for i in range(1, len(s)):
            if s[i] == s[i - 1]:
                cur += 1
            else:
                pre, cur = cur, 1
            if pre >= cur:
                res += 1
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅