-
Notifications
You must be signed in to change notification settings - Fork 0
/
3234.cpp
48 lines (41 loc) · 1.26 KB
/
3234.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "bits/stdc++.h"
using namespace std;
class Solution {
public:
int numberOfSubstrings(string s) {
int n = s.size();
int ans = 0;
vector<int> prefix(n,0);
prefix[0] = (s[0] - '0' == 1 ? 1 : 0);
for (int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1] + (s[i] - '0' == 1 ? 1 : 0);
}
for (int i = 0; i < n; i++) {
int one = 0;
int zero = 0;
for (int j = i; j < n; j++) {
one = prefix[j] - (i == 0 ? 0 : prefix[i - 1]);
zero = (j - i + 1) - one;
//CASE->1
if ((zero * zero) > one) {
j += (zero * zero - one - 1);
}
else if ((zero * zero) == one) {
ans++;
}
else if ((zero * zero) < one) {
ans++;
int diff = sqrt(one) - zero;
int nextj = j + diff;
if (nextj >= n) {
ans += (n - j - 1);
} else {
ans += diff;
}
j = nextj;
}
}
}
return ans;
}
};