Skip to content

Commit 20d8686

Browse files
committed
longest balance 0s and 1s string
1 parent 2aca118 commit 20d8686

2 files changed

Lines changed: 61 additions & 1 deletion

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import java.util.HashMap;
2+
3+
/**
4+
Problem: Given a string which contains only 1 and 0,
5+
find out its longest sub-string that contains equal number of “1” and “0”.
6+
It should be done in O(n) time, O(n) space.
7+
8+
Example: “111100? => 1100, “00110? => 0110, “001111111000? => 111000.
9+
10+
We can use an array index to store the difference
11+
between the number of 1s and the number of 0s up to each character in string S.
12+
That is,we create an array diff with size equals to S.length + 1.
13+
diff[i] is the number of “1”s appeared up to the ith character in S
14+
subtracts the number of “0”s appeared up to ith character in S.
15+
16+
To be more specific, we have this counter initially set to 0,
17+
if we meet a “1”, then counter increases by 1.
18+
Otherwise the counter decreases by 1.
19+
How long is the longest “1 and 0” balanced substring?
20+
That is the longest distance between two identical counter in diff.
21+
Because the counters are the same, they should meet same number of “1”s and “0”s in between.
22+
23+
*/
24+
public class LongestBalanceSubstring {
25+
public static void main(String[] args){
26+
String s = "1001110010001";
27+
String balanceString = longestBalanceSubstring(s);
28+
System.out.println(balanceString);
29+
30+
String s1 = "0101001";
31+
String balanceString1 = longestBalanceSubstring(s1);
32+
System.out.println(balanceString1);
33+
34+
}
35+
public static String longestBalanceSubstring(String s){
36+
if(s.length() <=0)
37+
return "";
38+
int[] diffCounter = new int[s.length()+1];
39+
diffCounter[0] = 0;
40+
for(int i= 0; i < s.length(); i++){
41+
diffCounter[i+1] = diffCounter[i] + ((s.charAt(i) == '0')? -1:1);
42+
}
43+
HashMap<Integer, Integer> counterIndex = new HashMap<Integer, Integer>();
44+
for(int i = 1, j = diffCounter.length-1; i < j;){
45+
if(!counterIndex.containsKey(diffCounter[i])){
46+
counterIndex.put(diffCounter[i], i-1);
47+
i++;
48+
}else {
49+
return s.substring(i,j);
50+
}
51+
if(!counterIndex.containsKey(diffCounter[j])){
52+
counterIndex.put(diffCounter[j], j-1);
53+
j--;
54+
}else {
55+
return s.substring(i-1,j);
56+
}
57+
}
58+
return "";
59+
}
60+
}

PuzzleCoding/src/ThreeSumClosest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ public static int[] threeSumClosest(int[] a, int target) {
9393
return result;
9494
}
9595

96-
// non binary search
96+
// non binary search O(n^3)
9797
public static int[] threeSumClosest1(int[] a, int target) {
9898
int[] result = new int[3];
9999

0 commit comments

Comments
 (0)