题目
思路
本题重要的一点在于: count的初始值为1而不是0主旨思想是 不断遍历当前数组,当前后仙童时,置count为1,不相同,count++ 与max比较
最大值永远存放在 max里面,count用于统计每一块的长度
代码
/**
*
*/
package 交错01串;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/***
* @author 18071
* @Date 2019年3月19日 功能:如果一个01串任意两个相邻位置的字符都是不一样的,我们就叫这个01串为交错01串。例如:
* "1","10101","0101010"都是交错01串。
* 小易现在有一个01串s,小易想找出一个最长的连续子串,并且这个子串是一个交错01串。小易需要你帮帮忙求出最长的这样的子串的长度是多少。
***/
public class test {
/***
* @author SG CV-6
* @Date 2019年3月19日 功能:
* @param args
***/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
String[] sa = s.nextLine().split("");
int[] aa = new int[sa.length];
for (int i = 0; i < sa.length; i++) {
aa[i] = Integer.parseInt(sa[i]);
}
// 快慢指针 --
int fast = 1;
int slow = 0;
int count = 1;
int max = 1;
while (fast < aa.length) {
if (aa[slow] == aa[fast]) {
count = 1;
slow++;
fast++;
}
if (fast < aa.length && slow < aa.length) {
if (aa[slow] != aa[fast]) {
//System.out.println(slow+ " "+fast );
count++;
//System.out.println("count is "+count);
if (max < count) {
max = count;
}
if (fast < aa.length && slow < aa.length) {
fast++;
slow++;
}
}
}
}
System.out.println(max);
}
}