2609. Find the Longest Balanced Substring of a Binary String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int findTheLongestBalancedSubstring(String s) {
int maxLength = 0;

for (int i = 0; i < s.length() - 1; i++) {
// 中心扩散
maxLength = Math.max(maxLength, tryExpand(s, i, i + 1));
}

return maxLength;
}

private int tryExpand(String s, int i, int j) {
while (i >= 0 && j < s.length() && s.charAt(i) == '0' && s.charAt(j) == '1') {
i--;
j++;
}
return j - i - 1;
}
}
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
class Solution {
public int findTheLongestBalancedSubstring(String s) {
int maxLength = 0;

int[] counts = new int[2];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '0') {
if (i == 0 || s.charAt(i - 1) == '1') {
// 重置计数
counts[0] = 1;
counts[1] = 0;
} else {
counts[0]++;
}
} else {
// c == '1'
counts[1]++;
maxLength = Math.max(maxLength, 2 * Math.min(counts[0], counts[1]));
}
}

return maxLength;
}
}

References

2609. Find the Longest Balanced Substring of a Binary String