1513. Number of Substrings With Only 1s

time: O(n)

space: O(1)

class Solution {
    public int numSub(String s) {
        int result = 0;
        int n = s.length();
        
        int j = 1;
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '0') {
                continue;
            }
            
            j = Math.max(j, i+1);
            while (j < n && s.charAt(j) == '1') {
                j++;
            }
            result = (result + (j - i)) % ((int)1e9 + 7);
        }
        return result;
    }
}

Last updated