LeetCode: Longest Substring Without Repeating Characters

Description: Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letter for "abcabcbb" is "abc", which the length is 3. For "bbbb" the longest substring is "b", with the length is 1.

根据题目意思,就是在一个字符串中找不存在重复字符的最大连续子字符串,并返回子字符串对应的长度。

通过分析题目,我发现有以下两个问题需要明确:

1、字符串的构成是什么?

2、如何找出满足条件的子字符串并确定其对应的长度为最大?

对于问题1,由于题目没有规定相应的字符串构成,因此在实现的过程中,我们必须考虑所有可能的字符,即256种字符(切记不是只有大小写字母、数字以及标点符号)。

对于问题2,我们可以进行如下分析:

首先:由于所求的子字符串的位置不确定,因此我们可以使用从头遍历的方式进行确定起始位置,如下图所示:


其次:固定起始位置,然后向后遍历依次判断后面的字符是否出现在当前子字符串(从start到当前位置)中:

1)如果遍历的字符没有出现,则继续向后遍历;


2)如果当前遍历到的字符和start对应字符相同(s[k] == s[i]),则计算出一个子字符串的长度,并将start位置向后移动一位,length = end - start


3)如果当前遍历到的字符不与start位置对应的字符相同,而是与start之后的一个字符相同,则length = end - start,并且将start移到相同的字符后一位,然后end继续后移。例如,end对应的字符与第m个字符相同(s[j] == s[m]),则过程如下:


明确了整个算法过程,我们便可以很容易写出相应代码,如下所示:

public int lengthOfLongestSubstring(String s) {
		if (s == null || s.length() == 0)
			return 0;
		
		<span style="color:#ff0000;">boolean[] index = new boolean[256];</span>   //每个字符是否已经在前面出现 
		int maxLength = 0;
		int start = 0, end = 0;
		for(; end<s.length(); end++) {
			if(index[s.charAt(end)]) {  //当前字符已在前面扫描中存在
				int len = end - start;
				maxLength = maxLength>len ? maxLength:len;
				<span style="color:#ff0000;">while (s.charAt(start) != s.charAt(end)) { //字符在中间存在
					index[s.charAt(start)] = false;
					start++;
				}</span>
				start++;
			} else {
				index[s.charAt(end)] = true;
			}
		}
		maxLength = maxLength>(end-start) ? maxLength:(end-start);
		
		return maxLength;
    }


猜你喜欢

转载自blog.csdn.net/yangfeisc/article/details/41556651