题目
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
题意
从字符串中找出最长不重复子串的长度
思路
首先想到二重循环,提交果断超时。改为一旦重复,则仅对子串的首尾进行操作,然后开始下次判断
代码
int lengthOfLongestSubstring(char* s) {
int i,j,max=0,num=0,flag[300]={0};
for(i=0;i<strlen(s);i++)
{
j=i+num;
if(!flag[(int)(s[j])])
{
while(!flag[(int)(s[j])] && j<strlen(s))
{
num++;
flag[(int)(s[j])]=1;
j++;
}
flag[(int)(s[i])]=0;
if(num>max)
{
max=num;
}
num--;
}
else
{
flag[(int)(s[i])]=0;
num--;
}
}
return max;
}