Number of Substrings With Only 1s

Given a binary string s (a string consisting only of '0' and '1's).

Return the number of substrings with all characters 1's.

Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.

思路1:统计有多少个连续的1,然后根据大小长度,频率记录下来,然后每个大小,是一个count,最后加起来就是答案;tricky的是最后一个连续的1,i要单独判断一下,如果是1,那么hashmap还要加入最后一个count;

class Solution {
    public int numSub(String s) {
        int MOD = 1000000007;
        HashMap<Integer, Integer> hashmap = new HashMap<>();
        char[] ss = s.toCharArray();
        
        int count = 0;
        int i = 0;
        for(; i < ss.length; i++) {
            if(ss[i] == '1') {
                count++;
            } else {
                hashmap.put(count, hashmap.getOrDefault(count, 0) + 1);
                count = 0;
            }
        }
        if(ss[n - 1] == '1') {
            hashmap.put(count, hashmap.getOrDefault(count, 0) + 1);
        }
        
        int res = 0;
        for(Integer key: hashmap.keySet()) {
            res = res % MOD + ( getSum(key, MOD) % MOD * hashmap.get(key) % MOD ) % MOD;
        }
        return res;
    }
    
    private int getSum(int len, int MOD) {
        int res = 0;
        for(int i = len; i >= 1; i--) {
            res = res % MOD + i % MOD;
        }
        return res;
    }
}

思路2: dp, 0110111, 0120123,dp[i] 表示的物理意义就是到目前为止,1的个数;

class Solution {
    public int numSub(String s) {
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = 0;
        int MOD = 1000000007;
        int sum = 0;
        for(int i = 1; i <= n; i++) {
            if(s.charAt(i - 1) == '1') {
                dp[i] = dp[i - 1] + 1;
            } else {
                dp[i] = 0;
            }
            sum = sum % MOD + dp[i] % MOD;
        }
        return sum % MOD;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值