Number of Substrings With Only 1s LeetCode solution in C++

1
class Solution {
2
/*
3
To calculate the substring the formula is (n*n+1)/2 so just find the range and
4
calculate the substrings.
5
*/
6
int mod = 1e9 + 7;
7
long calculateNumbeOfSubstrings(string &s, int &l, int &r) {
8
long range = r - l;
9
long ans = range * (range + 1) / 2;
10
return ans;
11
}
12

13
public:
14
int numSub(string s) {
15
int ans = 0;
16
int len = s.size();
17
int r = 0, l = 0;
18
while (r < len) {
19
while (r < len && s[l] != '1') {
20
l++;
21
r++;
22
}
23
while (r < len && s[r] != '0') {
24
r++;
25
}
26
ans = (ans + calculateNumbeOfSubstrings(s, l, r)) % mod;
27
l = r;
28
}
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0