You are given a binary string s consisting only of zeroes and ones.
A substring of s is considered balanced ifall zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring.
Notice that the empty substring is considered a balanced substring.
Return the length of the longest balanced substring ofs.
A substring is a contiguous sequence of characters within a string.
A balanced substring must have all 0s before all 1s and equal numbers of each. By counting consecutive groups of 0s and 1s, the maximum balanced substring at each transition is twice the minimum of the current 0-group and 1-group.
classSolution {
public:int findTheLongestBalancedSubstring(string s) {
int ans =0, cnt0 =0, cnt1 =0;
for (char c : s) {
if (c =='0') {
if (cnt1 >0) cnt0 =0;
cnt0++;
cnt1 =0;
} else {
cnt1++;
ans = max(ans, 2* min(cnt0, cnt1));
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcfindTheLongestBalancedSubstring(sstring) int {
ans, cnt0, cnt1:=0, 0, 0for_, c:=ranges {
ifc=='0' {
ifcnt1 > 0 { cnt0 = 0 }
cnt0++cnt1 = 0 } else {
cnt1++if2*min(cnt0, cnt1) > ans {
ans = 2* min(cnt0, cnt1)
}
}
}
returnans}
func min(a, bint) int { ifa < b { returna }; returnb }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintfindTheLongestBalancedSubstring(String s) {
int ans = 0, cnt0 = 0, cnt1 = 0;
for (char c : s.toCharArray()) {
if (c =='0') {
if (cnt1 > 0) cnt0 = 0;
cnt0++;
cnt1 = 0;
} else {
cnt1++;
ans = Math.max(ans, 2 * Math.min(cnt0, cnt1));
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funfindTheLongestBalancedSubstring(s: String): Int {
var ans = 0; var cnt0 = 0; var cnt1 = 0for (c in s) {
if (c =='0') {
if (cnt1 > 0) cnt0 = 0 cnt0++ cnt1 = 0 } else {
cnt1++ ans = maxOf(ans, 2 * minOf(cnt0, cnt1))
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
deffind_the_longest_balanced_substring(s: str) -> int:
ans = cnt0 = cnt1 =0for c in s:
if c =='0':
if cnt1 >0:
cnt0 =0 cnt0 +=1 cnt1 =0else:
cnt1 +=1 ans = max(ans, 2* min(cnt0, cnt1))
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnfind_the_longest_balanced_substring(s: String) -> i32 {
let (mut ans, mut cnt0, mut cnt1) = (0, 0, 0);
for c in s.chars() {
if c =='0' {
if cnt1 >0 { cnt0 =0; }
cnt0 +=1;
cnt1 =0;
} else {
cnt1 +=1;
ans = ans.max(2* cnt0.min(cnt1));
}
}
ans
}
}