#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX(a ,b) ((a)<(b)? (b):(a))
int lengthOfLongestSubstring2(char * s)
{
int hash[127] = {0};
int left = 0,right = 0,max =0;
while(s[right])
{
if (hash[s[right]] && (left < hash[s[right]]))
{
left = hash[s[right]] ;
}
hash[s[right]] = right + 1;
max = MAX(max,(right - left +1));
right++;
}
return max;
}
int lengthOfLongestSubstring3(char * s)
{
int hash[127] = {0};
int left = 0,right = 0,max =0;
while (s[right])
{
if (hash[s[right]]==0)
{
hash[s[right++]]++;
}
else
{
hash[s[left++]]--;
}
max = MAX(max,(right-left));
}
return max;
}
int main(int *argc,char *argv[])
{
char * s ="dbbabcabc";
int temp =0;
temp = lengthOfLongestSubstring1(s);
printf("algorithm1 temp =%d\n",temp);
temp = lengthOfLongestSubstring2(s);
printf("algorithm2 temp =%d\n",temp);
temp = lengthOfLongestSubstring3(s);
printf("algorithm3 temp =%d\n",temp);
}
使用hash表,记录字符出现的次数,用左右指针制造滑动窗口。如果hash为0,右指针增加,并且对应的hash表加一;如果hash不为0,左指针增加,hash减一。记录最长字符串长度。