Skip to content

Commit 75382b2

Browse files
solves #2609: FindTheLongestBalancedSubstringOfABinaryString in java
1 parent 9831a36 commit 75382b2

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

README.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -811,8 +811,7 @@
811811
| 2595 | [Number of Even and Odd Bits](https://leetcode.com/problems/number-of-even-and-odd-bits) | [![Java](assets/java.png)](src/NumberOfEvenAndOddBits.java) | |
812812
| 2600 | [K Items With the Maximum Sum](https://leetcode.com/problems/k-items-with-the-maximum-sum) | [![Java](assets/java.png)](src/KItemsWithTheMaximumSum.java) | |
813813
| 2605 | [Form Smallest Number From Two Digit Arrays](https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays) | [![Java](assets/java.png)](src/FormSmallestNumberFromTwoDigitArrays.java) | |
814-
| 2605 | [Form Smallest Number From Two Digit Arrays](https://leetcode.com/problems/form-smallest-number-from-two-digit-arrays) | | |
815-
| 2609 | [Find the Longest Balanced Substring of a Binary String](https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string) | | |
814+
| 2609 | [Find the Longest Balanced Substring of a Binary String](https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string) | [![Java](assets/java.png)](src/FindTheLongestBalancedSubstringOfABinaryString.java) | |
816815
| 2614 | [Prime In Diagonal](https://leetcode.com/problems/prime-in-diagonal) | | |
817816
| 2639 | [Find the Width of Columns of a Grid](https://leetcode.com/problems/find-the-width-of-columns-of-a-grid) | | |
818817
| 2643 | [Row With Maximum Ones](https://leetcode.com/problems/row-with-maximum-ones) | | |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/find-the-longest-balanced-substring-of-a-binary-string
2+
// T: O(n)
3+
// S: O(1)
4+
5+
public class FindTheLongestBalancedSubstringOfABinaryString {
6+
public int findTheLongestBalancedSubstring(String s) {
7+
int result = 0;
8+
for (int maxZeros = 0, maxOnes = 0, i = 0 ; i < s.length() ; i++) {
9+
if (s.charAt(i) == '0') {
10+
if (i - 1 >= 0 && s.charAt(i - 1) == '1') {
11+
result = Math.max(result, 2 * Math.min(maxOnes, maxZeros));
12+
maxOnes = 0;
13+
maxZeros = 1;
14+
} else {
15+
maxZeros++;
16+
}
17+
} else {
18+
maxOnes++;
19+
if (i == s.length() - 1) {
20+
result = Math.max(result, 2 * Math.min(maxOnes, maxZeros));
21+
}
22+
}
23+
}
24+
return result;
25+
}
26+
}

0 commit comments

Comments
 (0)