/**
*
* 数字串,全为0,1组合而成。求一个最长的连续子串,其中0和1的个数相等。
* 比如: 01100111 --> 011001
* 110000011 --> 1100 / 0011
*
* 方法:
* 定义一个数组a,a[0] = 0
* 然后遍历输入输入数字串,遇到0,减1,遇到1,加1。含义就是,到目前位置,净值出现了多少个0或者1.
* 在数组a中选择两个相等的值,比如都是-3,第一个-3表示到该元素为止,多出现了3个0,第二个-3还是表示
* 到该元素为止,多出3个0,那么这两个元素之间的0和1的个数必定相互抵消。
* 于是,所求子串等同于,数组a中距离最远的两个相同值。可以两次循环,复杂度o(n*n)
*
* 为了O(n)的复杂度,利用hash表代替数组。原理一样。
*
**/
public class ZeroOnePairs {
public static void find(int[] input){
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, 0);
int begin = 0;
int max = 0;
int current = 0;
for(int i=0; i<input.length; i++){
if(input[i] == 0){
current--;
}else{
current++;
}
Integer p = map.get(current);
if(p == null){
map.put(current, i+1);
}else{
int l = p.intValue();
if((i+1-l) > max){
max = i + 1 - l;
begin = l;
}
}
}
for(int j=begin; j<begin+max; j++){
System.out.print(input[j]);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// int[] input = {0,1,1,0,0,1,1,1};
int[] input = {1,0,0,0,0,0,1,1};
ZeroOnePairs.find(input);
}
}