Given a binary string s, return the number of non-empty substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Input: s ="00110011"Output: 6Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's:"0011","01","1100","10","0011", and "01".Notice that some of these substrings repeat and are counted the number of times they occur.Also,"00110011"is not a valid substring because all the 0's (and 1's) are not grouped together.
The key is to count consecutive groups of 0’s and 1’s. For each pair of adjacent groups, the number of valid substrings is the minimum of their lengths. This works because a valid substring must have equal numbers of consecutive 0’s and 1’s, and all 0’s and all 1’s must be grouped together.
classSolution {
public:int countBinarySubstrings(string s) {
int ans =0, prev =0, cur =1;
for (int i =1; i < s.size(); ++i) {
if (s[i] == s[i-1]) {
cur++;
} else {
ans += min(prev, cur);
prev = cur;
cur =1;
}
}
ans += min(prev, cur);
return ans;
}
};
funccountBinarySubstrings(sstring) int {
ans, prev, cur:=0, 0, 1fori:=1; i < len(s); i++ {
ifs[i] ==s[i-1] {
cur++ } else {
ifprev < cur {
ans+=prev } else {
ans+=cur }
prev = curcur = 1 }
}
ifprev < cur {
ans+=prev } else {
ans+=cur }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintcountBinarySubstrings(String s) {
int ans = 0, prev = 0, cur = 1;
for (int i = 1; i < s.length(); ++i) {
if (s.charAt(i) == s.charAt(i-1)) {
cur++;
} else {
ans += Math.min(prev, cur);
prev = cur;
cur = 1;
}
}
ans += Math.min(prev, cur);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funcountBinarySubstrings(s: String): Int {
var ans = 0var prev = 0var cur = 1for (i in1 until s.length) {
if (s[i] == s[i-1]) {
cur++ } else {
ans += minOf(prev, cur)
prev = cur
cur = 1 }
}
ans += minOf(prev, cur)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defcountBinarySubstrings(self, s: str) -> int:
ans =0 prev =0 cur =1for i in range(1, len(s)):
if s[i] == s[i-1]:
cur +=1else:
ans += min(prev, cur)
prev = cur
cur =1 ans += min(prev, cur)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfncount_binary_substrings(s: String) -> i32 {
let s = s.as_bytes();
letmut ans =0;
letmut prev =0;
letmut cur =1;
for i in1..s.len() {
if s[i] == s[i-1] {
cur +=1;
} else {
ans += prev.min(cur);
prev = cur;
cur =1;
}
}
ans += prev.min(cur);
ans
}
}