-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsolution.cpp
More file actions
34 lines (26 loc) · 1.03 KB
/
solution.cpp
File metadata and controls
34 lines (26 loc) · 1.03 KB
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
class Solution {
public:
int countBinarySubstrings(string s) {
int n = s.length();
int prevGroup = 0; // length of previous group
int currGroup = 1; // length of current group (start with 1)
int result = 0; // final answer
for (int i = 1; i < n; i++) {
if (s[i] == s[i - 1]) {
// Same character, increase current group size
currGroup++;
} else {
// Character changed, so we finish one group
// Add min of previous and current group
result += min(prevGroup, currGroup);
// Update previous group
prevGroup = currGroup;
// Reset current group
currGroup = 1;
}
}
// Add the last comparison
result += min(prevGroup, currGroup);
return result;
}
};