最长不重复子串

最长不重复子串

题目描述:

最长不重复子串就是从一个字符串中找到一个连续子串,该子串中任何两个字符都不能相同,且该子串的长度是最大的。

输入:

输入包含多个测试用例,每组测试用例输入一行由小写英文字符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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值