//求无重复字符最长字串
// 思想:
//(1)for循环,遍历每一个字符,求出以其作为首字母的子串长度;
//(2)循环比较长度,选择最长的子串进行输出
#include<stdio.h>
#include<string.h>
int lengthOfLongestSubstring(char * s);
int main()
{
char s[10];
scanf("%s",s);
printf("%d",lengthOfLongestSubstring(s));
return 0;
}
int lengthOfLongestSubstring(char * s){
int n=strlen(s);
int count[50000];
int flag=0;
int i,t=0;
for(i=0;i<n;i++)
{
if(s[i]!=s[i+1]&&s[i+1]!=NULL)
{
count[i]=2;
}
else
{
count[i]=1;
}
for(int j=count[i]+i;j<n;j++)//遍历字串之后的字符
{
for(int h=i;h<i+count[i];h++)//遍历已有的字串
{
if(s[j]==s[h])//判断该字符是否与已有的重复
{
flag=1;
break;
}
}
if(flag==0)//没有重复的串,加一
{
count[i]++;
}
else
{
flag=0;
break;
}
}
}
for(i=0;i<n;i++)//选择最大的字串长度输出
{
if(t<count[i])
{
t=count[i];
}
}
return t;
}
我的解题思路比较简单,在时间和空间的开销上没有考虑太多。如果要进一步减小时间和空间的开销,可以在我代码的基础上考虑改进。
如果有其他更好解法的话,可以在评论区call我。