Skip to content

Commit 212e219

Browse files
committed
2609. Find the Longest Balanced Substring of a Binary String
1 parent 33032b7 commit 212e219

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.doublejony.leetcode;
2+
3+
import com.google.common.base.Stopwatch;
4+
import com.tngtech.java.junit.dataprovider.DataProvider;
5+
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
6+
import com.tngtech.java.junit.dataprovider.UseDataProvider;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
10+
import static com.doublejony.common.AssertResolve.resolve;
11+
12+
@RunWith(DataProviderRunner.class)
13+
public class Leet2609 {
14+
15+
@DataProvider
16+
public static Object[][] testCase() {
17+
// @formatter:off
18+
return new Object[][]{
19+
{
20+
"001",
21+
2
22+
},
23+
{
24+
"01000111",
25+
6
26+
},
27+
{
28+
"00111",
29+
4
30+
},
31+
{
32+
"111",
33+
0
34+
},
35+
};
36+
// @formatter:on
37+
}
38+
39+
@Test
40+
@UseDataProvider("testCase")
41+
public void solution(String s, int expected) {
42+
43+
Stopwatch timer = Stopwatch.createStarted();
44+
resolve(Thread.currentThread().getStackTrace()[1].getMethodName(), expected,
45+
new Solution().findTheLongestBalancedSubstring(s), timer.stop());
46+
}
47+
48+
class Solution {
49+
50+
public int findTheLongestBalancedSubstring(String s) {
51+
int zCount = 0;
52+
int oCount = 0;
53+
boolean isOne = false;
54+
55+
int answer = 0;
56+
for (int i = 0; i < s.length(); i++) {
57+
char c = s.charAt(i);
58+
switch (c) {
59+
case '0':
60+
if (isOne) {
61+
zCount = 0;
62+
oCount = 0;
63+
isOne = false;
64+
}
65+
zCount++;
66+
break;
67+
case '1':
68+
oCount++;
69+
isOne = true;
70+
break;
71+
}
72+
73+
if (zCount >= oCount) {
74+
answer = Math.max(answer, oCount * 2);
75+
}
76+
}
77+
78+
return answer;
79+
}
80+
}
81+
82+
}

0 commit comments

Comments
 (0)