Skip to content

1513. Number of Substrings With Only 1s 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int numSub(string s) {
    constexpr int kMod = 1'000'000'007;

    int ans = 0;
    int l = -1;

    for (int i = 0; i < s.length(); ++i) {
      if (s[i] == '0')
        l = i;  // Handle the reset value.
      ans = (ans + i - l) % kMod;
    }

    return ans;
  }
};