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.
很简单的一道题,我用hashmap做的将每个字符的位置存入hash表中,如果有重复的字符已经在表中时更新t_start,t_end
,将hash表置空然后继续遍历字串s
每次更新最长时的状态和index.然后返回就ok了~
int hash_map[128]={0};
int lengthOfLongestSubstring(char* s) {
memset(hash_map,0, sizeof(hash_map));
int i=0;
int start=0;
int end = 0;
int t_start,t_end;
int key = 0;
int length=0;
int t_length=0;
t_start=0;
t_end=-1;
while (s[i]!='\0') {
key = (int)s[i];
if(hash_map[key] == 0)
{
hash_map[key] = i+1;
t_end++;
t_length = t_end - t_start+1;
}
else
{ int temp = t_start;
t_start = hash_map[key]-1+1;
t_end = i;
t_length = 1;
for (int j = temp; j < t_start; j++) {
hash_map[(int)s[j]] = 0;
}
hash_map[key] = i+1;
}
if(t_length>length)
{
start = t_start;
end = t_end;
length = t_length;
}
i++;
}
return length;
}