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.
统计0和1数目相等且所有0和1都在一起的子字符串的数量

思路:
把源字符串0和1的数量统计出来并分组
比如说00110011 写作数组 2222, 即2个0,2个1,2个0,2个1
再比如00001110011 写作数组 4322, 即4个0,3个1,2个0,2个1
数组相邻元素求较小值并累加, 原理是:拿第二个例子来说,4个0和3个1组成的满足条件的子字符串的数量受制于3(4和3的较小者);3个1和2个0组成的满足条件的子字符串的数量受制于2(3和2的较小者),2个0和2个1组成的满足条件的子字符串的数量受制于2(2和2的较小者)。

代码如下:

class Solution {
    public int countBinarySubstrings(String s) {
        List<Integer> list=new ArrayList<>();
        int counter=1;
        for(int i=1; i<s.length(); i++){
            if(s.charAt(i-1)!=s.charAt(i)){
                list.add(counter);
                counter=1;
            }
            else{
                counter++;
            }
        }
        list.add(counter);
        counter=0;
        for(int i=1; i<list.size(); i++){
            counter+=Math.min(list.get(i-1), list.get(i));
        }
        return counter;
    }
}

时间复杂度:O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值