Skip to content

Commit a16bae3

Browse files
authored
Create count-substrings-that-satisfy-k-constraint-i.cpp
1 parent 09f377e commit a16bae3

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// two pointers, sliding window
5+
class Solution {
6+
public:
7+
int countKConstraintSubstrings(string s, int k) {
8+
int result = 0;
9+
for (int right = 0, left = 0, cnt = 0; right < size(s); ++right) {
10+
cnt += s[right] == '1' ? 1 : 0;
11+
while (!(cnt <= k || (right - left + 1) - cnt <= k)) {
12+
cnt -= s[left++] == '1' ? 1 : 0;
13+
}
14+
result += right - left + 1;
15+
}
16+
return result;
17+
}
18+
};

0 commit comments

Comments
 (0)