Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"Output: 3 Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: "bbbbb"Output: 1Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: "pwwkew"Output: 3Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
设置了low和high建立一个滑动窗口,出现重复就往后挪,每次计算子串最大长度
int lengthOfLongestSubstring(char * s){
int count=0,flag=0,high=0,low=0;
for(int i=0;s[i];i++){
for(int j=low;j<i;j++)
if(s[i]==s[j]){
flag=j;
low=flag+1;
}
high=i;
if(high-low+1>count)count=high-low+1;
printf("low=%d;high=%d;count=%d\n",low, high,count);
}
return count;
}
Tips:
strlen(s)==0为字符串判空条件。空字符串“”实际是“\0”,但使用这个进行判断的话经常会报错 虽然最后根本没有进行判空
printf(“low=%d;high=%d;count=%d\n”,low, high,count);学会用输出语句进行调试
本题依然可以使用哈希表进行优化,参考代码↓ 作者:wu-sheng-23
int lengthOfLongestSubstring(char * s){
int i, j = 0, count = 0, max = 0, index[128] = {0}, start = 0;
for(i=0;s[i]!='\0';i++)
{
if(index[s[i]]>start) //index用来储存出现重复字符时
{ //子串起始下标应移动到的地方
count = i-start;
if(count>max)
max = count;
start = index[s[i]];
}
index[s[i]] = i+1;
}
count = i-start;
return count>max?count:max;
}
index中每个值存储的是某一字符最后出现的地方的下一位,假如下次遇到相同字符(该字符在index中的值在原起始点之后,即字串中包含了重复字符出现的位置)时通过检索index即可将子串起始点移到该位置
用哈希表空间换时间,之后也要多练习