题目地址:http://ac.jobdu.com/problem.php?pid=1530
-
题目描述:
-
最长不重复子串就是从一个字符串中找到一个连续子串,该子串中任何两个字符都不能相同,且该子串的长度是最大的。
-
输入:
-
输入包含多个测试用例,每组测试用例输入一行由小写英文字符a,b,c...x,y,z组成的字符串,字符串的长度不大于10000。
-
输出:
-
对于每组测试用例,输出最大长度的不重复子串长度。
-
样例输入:
-
absd abba abdffd
-
样例输出:
-
4 2 4
#include <stdio.h>
int MaxLength(char str[]){
int index = 0;
int i;
int tmp = 0;
int max = 0;
int hash[26];
int alphabet;
for (i=0; i<26; ++i)
hash[i] = 0;
while (str[index]){
alphabet = str[index] - 'a';
if (hash[alphabet] == 0){
hash[alphabet] = 1;
if (++tmp > max)
max = tmp;
}
else{
for (i=0; i<26; ++i)
hash[i] = 0;
hash[str[index] - 'a'] = 1;
i = index - 1;
while (i >= 0 && str[i] != str[index]){
alphabet = str[i] - 'a';
hash[alphabet] = 1;
--i;
}
tmp = index - i;
}
++index;
}
return max;
}
int main(void){
char str[10010];
while (scanf ("%s", str) != EOF){
printf ("%d\n", MaxLength(str));
}
return 0;
}
本文介绍了一种求解最长不重复子串的算法实现,通过遍历字符串并使用哈希表记录字符出现的位置,来高效地寻找最长的不包含重复字符的子串。文章提供了一个完整的C语言实现示例,并通过具体的样例输入输出展示了算法的有效性。
1773

被折叠的 条评论
为什么被折叠?



