leetcode 696. Count Binary Substrings

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.

Example 1:

Input: "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: "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Note:

  • s.length will be between 1 and 50,000.
  • s will only consist of "0" or "1" characters.

解法1:

使用两个计数器,记录连续1和0的次数。每次循环时候,如果当前数字的计数器比之前数字的计数器数值小,则ans+=1。

计数细节:看到计数连续出现的字符,当s[i]==s[i-1],计数器+=1,否则reset计数器,将上次的计数存起来。

复制代码
class Solution(object):
    def countBinarySubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        # 00     11         00   11
        #  |      |          |    |
        #cnt=2   new_cnt=2 cnt=2 new_cnt=2
        #    ans +=2    ans+=2   ans+=2
        ans = 0
        cnt = 1
        pre_cnt = 0
        for i in xrange(1, len(s)):
            if s[i]==s[i-1]:
                cnt += 1
            else:
                pre_cnt = cnt
                cnt = 1
            if pre_cnt >= cnt:
                ans += 1
        return ans        
复制代码

直接将连续的字符串计数器用数组记录起来,然后将结果加起来!此法更直观!!

  • '00001111' => [4, 4] => min(4, 4) => 4
  • '00110' => [2, 2, 1] => min(2, 2) + min(2, 1) => 3
  • '10101' => [1, 1, 1, 1, 1] => 4
复制代码
class Solution(object):
    def countBinarySubstrings(self, s):
        cnt = 1
        chunks = []
        for i in xrange(1, len(x)):
            if s[i] == s[i-1]:
                cnt += 1
            else:
                chunks.append(cnt)
                cnt = 1
        return sum(min(chunks[i], chunks[i-1]) for i in xrange(1, len(chunks)))            
复制代码

 上述解法有错,漏掉了s[-1]计数,修正后的:

复制代码
class Solution(object):
    def countBinarySubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        cnt = 1
        arr = []
        for i in range(1, len(s)):
            if s[i] == s[i-1]:
                cnt += 1
            else:
                arr.append(cnt)
                cnt = 1
        arr.append(cnt)
        return sum(min(arr[i], arr[i-1]) for i in range(1, len(arr)))
复制代码

 

 

posted @   bonelee  阅读(212)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示