解题思路
快指针和慢指针,map数组下标定义为字符的asic值,值为asic值对应字母下标最大值,slow到fast之间的距离即为最长长度
代码
//数组初始化函数
void initial(int array[])
{
int k;
for(k=0;k<1000;k++)
{
array[k]=-1;
}
}
int lengthOfLongestSubstring(char * s){
if(strcmp(s,"")==0)
{
return 0;
}
int fast;
int slow=0;
int max=-1;
int map[1000];
initial(map);
for(fast=0;s[fast];fast++)
{
//当前字符在map中并且当前字符对应的标记值应大于slow值,移动slow
if(map[s[fast]]!=-1&&map[s[fast]]>=slow)
{
slow=map[s[fast]]+1;
map[s[fast]]=fast;
}
//当前字符不在map中,保存下标位置
else
{
map[s[fast]]=fast;
}
//满足条件跟新max
if(fast-slow+1>max)
{
max=fast-slow+1;
}
}
return max;
}