LintCode 1870: number of substrings with all zeroes

1870. number of substrings with all zeroes

Given a string str containing only0 or 1, please return the number of substrings that are consist of 0 .

Example

Example 1:

Input:"00010011"

Output:9

Explanation:

There are 5 substrings of "0",

There are 3 substrings of "00",

There is 1 substring of "000".

So return 9

Example 2:

Input:"010010"

Output:5

Notice

1<=|str|<=30000


解法1:
把每段的0...0都找出来,得到range_len。记得每个range的substrings的个数是range_len * (range_len + 1) / 2。

class Solution {
public:
    /**
     * @param str: the string
     * @return: the number of substrings 
     */
    int stringCount(string &str) {
        int len = str.size();
        int range_len = 0, result = 0;

        for (int i = 0; i < len; ++i) {
            if (str[i] == '0') {
                range_len++;
            } else {
                result += range_len * (range_len + 1) / 2;
                range_len = 0;
            }
        }
        if (range_len > 0) result += range_len * (range_len + 1) / 2;
        return result;            
    }
};

解法2:

采用同向双指针,i是左指针,j是右指针。i指向0,j从i开始,遍历连续的0, 每个0会累加一个j-i+1。当j移到非0字符时,就不会累加0,而且j也不会移动。此时j要依靠j=max(i,j)来移动。不太好写。不如上面的方法好。
 

class Solution {
public:
    /**
     * @param str: the string
     * @return: the number of substrings 
     */
    int stringCount(string &str) {
        int len = str.size();
        int i = 0, j = 0;
        int res = 0;
        for (i = 0; i < len; i++) {
            if (str[i] != '0') continue;
            j = max(i, j);            
            while(j < len && str[j] == '0') {
                res += j - i + 1;
                j++;
            }
        }
        return res;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值