2020-05-30 04:23:24 +08:00
|
|
|
int lengthOfLongestSubstring(char *str)
|
|
|
|
{
|
2019-08-25 01:08:45 +08:00
|
|
|
int n = strlen(str);
|
|
|
|
|
2020-05-30 04:23:24 +08:00
|
|
|
if (!n)
|
|
|
|
return 0;
|
2019-08-25 01:08:45 +08:00
|
|
|
|
2022-01-12 01:28:27 +08:00
|
|
|
int L_len = 1; // length of longest substring
|
|
|
|
int C_len = 1; // length of current substring
|
2019-08-25 01:08:45 +08:00
|
|
|
|
2020-06-28 23:25:37 +08:00
|
|
|
int P_ind, i; // P_ind for previous index
|
|
|
|
int visited[256]; // visited will keep track of visiting char for the last
|
|
|
|
// instance. since there are 256 ASCII char, its size is
|
|
|
|
// limited to that value.
|
2019-08-25 01:08:45 +08:00
|
|
|
memset(visited, -1, sizeof(int) * 256);
|
2020-05-30 04:23:24 +08:00
|
|
|
visited[str[0]] =
|
2020-06-28 23:25:37 +08:00
|
|
|
0; // the index of that char will tell us that when it was visited.
|
2019-08-25 01:08:45 +08:00
|
|
|
for (i = 1; i < n; i++)
|
|
|
|
{
|
2020-05-30 04:23:24 +08:00
|
|
|
P_ind = visited[str[i]];
|
2019-08-25 01:08:45 +08:00
|
|
|
if (P_ind == -1 || i - C_len > P_ind)
|
2020-06-28 23:25:37 +08:00
|
|
|
C_len++; // if the current char was not visited earlier, or it is
|
|
|
|
// not the part of current substring
|
2019-08-25 01:08:45 +08:00
|
|
|
else
|
2020-06-28 23:25:37 +08:00
|
|
|
{ // otherwise, we need to change the current/longest substring length
|
2020-05-30 04:23:24 +08:00
|
|
|
if (C_len > L_len)
|
|
|
|
L_len = C_len;
|
2019-08-25 01:08:45 +08:00
|
|
|
C_len = i - P_ind;
|
|
|
|
}
|
|
|
|
visited[str[i]] = i;
|
|
|
|
}
|
2020-05-30 04:23:24 +08:00
|
|
|
if (C_len > L_len)
|
|
|
|
L_len = C_len;
|
2019-08-25 01:08:45 +08:00
|
|
|
return L_len;
|
|
|
|
}
|
|
|
|
/* Brute force */
|
2020-05-30 04:23:24 +08:00
|
|
|
int lengthOfLongestSubstring(char *s)
|
|
|
|
{
|
2019-08-25 01:08:45 +08:00
|
|
|
int cur_max = 0, max = 0;
|
|
|
|
int counter[255];
|
|
|
|
int end = 0;
|
|
|
|
|
2020-05-30 04:23:24 +08:00
|
|
|
memset(counter, 0, sizeof(int) * 255);
|
|
|
|
while (end < strlen(s))
|
|
|
|
{
|
|
|
|
if (counter[s[end]] == 0)
|
|
|
|
{
|
2019-08-25 01:08:45 +08:00
|
|
|
counter[s[end]]++;
|
|
|
|
end++;
|
|
|
|
cur_max++;
|
2020-05-30 04:23:24 +08:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2019-08-25 01:08:45 +08:00
|
|
|
char c = s[end];
|
|
|
|
memset(counter, 0, 255 * sizeof(int));
|
|
|
|
if (cur_max >= max)
|
|
|
|
max = cur_max;
|
|
|
|
cur_max = 0;
|
2020-06-28 23:25:37 +08:00
|
|
|
while (s[end - 1] != c) end--;
|
2019-08-25 01:08:45 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (cur_max >= max)
|
|
|
|
max = cur_max;
|
|
|
|
return max;
|
|
|
|
}
|