[LeetCode] Find the Longest Balanced Substring of a Binary String

2609. Find the Longest Balanced Substring of a Binary String

You are given a binary string s consisting only of zeroes and ones.

A substring of s is considered balanced if all 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 of s.

A substring is a contiguous sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int findTheLongestBalancedSubstring(string s) {
int res = 0, one = 0, zero = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '0') {
if(one) one = 0, zero = 1;
else zero += 1;
} else if(s[i] == '1') {
one += 1;
res = min(res, 2 * min(one,zero));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/02/PS/LeetCode/find-the-longest-balanced-substring-of-a-binary-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.