LeetCode 1513: Number of Substrings With Only 1s

MathString

Problem Description

Explanation

To solve this problem, we can iterate through the binary string and count the continuous sequences of 1s. For every sequence of length n, the number of substrings that can be formed using that sequence is (n * (n + 1)) / 2. We calculate this for each sequence of 1s and sum up the results to get the total number of substrings with only 1s.

Solutions

class Solution {
    public int numSub(String s) {
        int count = 0;
        int result = 0;
        int mod = 1000000007;

        for (char c : s.toCharArray()) {
            if (c == '1') {
                count++;
            } else {
                result = (result + (count * (count + 1) / 2) % mod) % mod;
                count = 0;
            }
        }

        result = (result + (count * (count + 1) / 2) % mod) % mod;

        return result;
    }
}

Loading editor...