最长不重复子串
-
题目描述:
-
最长不重复子串就是从一个字符串中找到一个连续子串,该子串中任何两个字符都不能相同,且该子串的长度是最大的。
-
输入:
-
输入包含多个测试用例,每组测试用例输入一行由小写英文字符a,b,c...x,y,z组成的字符串,字符串的长度不大于10000。
-
输出:
-
对于每组测试用例,输出最大长度的不重复子串长度。
-
样例输入:
-
absd abba abdffd
-
样例输出:
-
4 2 4
package Array;
import java.util.Arrays;
import java.util.Scanner;
/**
* @Title: Longest_No_repeat.java
* @Package Array
* @Description: TODO
* @author nutc
* @date 2013-8-18 下午7:07:17
* @version V1.0
*/
public class Longest_No_repeat {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s = sc.nextLine();
char[] c = s.toCharArray();
System.out.println(find(c));
}
}
public static int find(char[] str) {
if (str == null)
return 0;
int[] count = new int[26];
Arrays.fill(count, -1);
int max = 0, nowmax = 0, nowstart = 0;
for (int i = 0; i < str.length; i++) {
int index = str[i] - 'a';
if (count[index] != -1 && count[index] >= nowstart) { // 第二个判断条件非常的重要!非常!!
nowmax -= (count[index] - nowstart + 1);
nowstart = count[index] + 1;
}
nowmax++;
count[index] = i;
if (nowmax > max)
max = nowmax;
}
return max;
}
}