【Lintcode】1870. number of substrings with all zeroes

题目地址:

https://www.lintcode.com/problem/number-of-substrings-with-all-zeroes/description

给定一个 0 − 1 0-1 01字符串 s s s,求其只含 0 0 0的子串个数。

考虑一个长度为 l l l的只含 0 0 0的字符串,则其所有子串都满足条件。考虑其有多少个子串。首先,其长度为 1 1 1的子串有 l l l个,其长度大于 1 1 1的子串的个数,等价于在 1 , . . . , l 1,...,l 1,...,l中选取两个数的方式数,所以是 ( l 2 ) = l ( l − 1 ) 2 \tbinom{l}{2}=\frac{l(l-1)}{2} (2l)=2l(l1);所以总共有 l + l ( l − 1 ) 2 = l ( l + 1 ) 2 l+\frac{l(l-1)}{2}=\frac{l(l+1)}{2} l+2l(l1)=2l(l+1)个子串。

接着只需要将 s s s中的最长 0 0 0子串都截出来累加起来即可。代码如下:

public class Solution {
    /**
     * @param str: the string
     * @return: the number of substrings
     */
    public int stringCount(String str) {
        // Write your code here.
        int res = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            // 找到0了,则将以它开头的最长0子串截出来
            if (ch == '0') {
                int j = i + 1;
                while (j < str.length() && str.charAt(j) == '0') {
                    j++;
                }
                
                // s[i, ..., j - 1]就是一个0子串,其子串个数是l(l + 1)/2
                res += (j - i) * (j - i + 1) / 2;
				// 将i移到0后面去
                i = j;
            }
        }
        
        return res;
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值