求字符串的不重复字符的最长子串长度的问题

已知一个字符串,只含有小写字母,求这个字符串的每个字符都不相同的最长子串的长度。

比如:

abcd 结果是4

abcab 结果是3


思路:

用一个26个元素的整形数组表示一个字符串中是否含有某个字符。a~b分别映射到数组元素0~25。

用两个指针分别指向字符串的第一个和第二个元素,用第二个指针从左往右扫描字符串。每扫描一个字符,根据数组中对应的值来判断这个字符是否已经出现。

如果没出现,则继续扫描,同时更新已知不相同子串的最大长度。

如果出现过,那么向右移动第一个指针,直到刚才重复的那个字符不再重复,然后继续上面的工作。


源代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int lns(char *str){
	int length, max = 1, temp;
	int i, j;
	int a[26];
	length = strlen(str);
	i = 0;
	while(i < 26)
		a[i++] = 0;
	a[str[0] - 'a'] = 1;
	i = 0;
	j = 1;
	temp = 1;
	while((j < length) && (i < length - max)){
		if(a[str[j] - 'a'] == 0){
			a[str[j] - 'a'] = 1;
			temp++;
			if(max < temp)
				max = temp;
			j++;
		}
		else{
			a[str[i] - 'a'] = 0;
			i++;
			temp--;
		}
	}
	return max;
}

int main(){
	char str[1024];
	scanf("%s", str);
	printf("length of longest non-repete substring: %d\n", lns(str));
	system("pause");
	return 0;	
}


posted @ 2014-11-09 20:46  simmerlee  阅读(126)  评论(0)    收藏  举报