|
| 1 | +// Time: O(n * sqrt(n)) = O(n^(3/2)) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +// two pointers, sliding window |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + int numberOfSubstrings(string s) { |
| 8 | + int result = 0; |
| 9 | + vector<int> idxs = {-1}; |
| 10 | + for (int i = 0; i < size(s); ++i) { |
| 11 | + if (s[i] == '0') { |
| 12 | + idxs.emplace_back(i); |
| 13 | + } |
| 14 | + } |
| 15 | + idxs.emplace_back(size(s)); |
| 16 | + for (int c = 0; c * c <= size(s); ++c) { |
| 17 | + for (int i = 0, left = 1, right = 1, cnt = 0; i < size(s); ++i) { |
| 18 | + if (idxs[right] == i) { |
| 19 | + ++right; |
| 20 | + } else { |
| 21 | + ++cnt; |
| 22 | + } |
| 23 | + if (right - left == c + 1) { |
| 24 | + cnt -= (idxs[left] - 1) - idxs[left - 1]; |
| 25 | + ++left; |
| 26 | + } |
| 27 | + if (!(right - left == c && cnt >= c * c)) { |
| 28 | + continue; |
| 29 | + } |
| 30 | + result += min((c ? idxs[left] : i) - idxs[left - 1], cnt - c * c + 1); |
| 31 | + } |
| 32 | + } |
| 33 | + return result; |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +// Time: O(n * sqrt(n)) = O(n^(3/2)) |
| 38 | +// Space: O(1) |
| 39 | +// two pointers, sliding window |
| 40 | +class Solution2 { |
| 41 | +public: |
| 42 | + int numberOfSubstrings(string s) { |
| 43 | + int result = 0; |
| 44 | + for (int c = 0; c * c <= size(s); ++c) { |
| 45 | + vector<int> cnt(2); |
| 46 | + for (int right = 0, left = 0, curr = 0; right < size(s); ++right) { |
| 47 | + ++cnt[s[right] == '1']; |
| 48 | + while (cnt[0] == c + 1) { |
| 49 | + --cnt[s[left++] == '1']; |
| 50 | + } |
| 51 | + if (!(cnt[0] == c && cnt[1] >= c * c)) { |
| 52 | + continue; |
| 53 | + } |
| 54 | + for (curr = max(curr, min(left, right)); curr < right; ++curr) { |
| 55 | + if (s[curr] == '0') { |
| 56 | + break; |
| 57 | + } |
| 58 | + } |
| 59 | + result += min(curr - left + 1, cnt[1] - c * c + 1); |
| 60 | + } |
| 61 | + } |
| 62 | + return result; |
| 63 | + } |
| 64 | +}; |
0 commit comments