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.
class Solution {
public:
int max(int a, int b)
{
return a > b ? a : b;
}
int lengthOfLongestSubstring(string s)
{
bool exist[27];
int pos[27];
memset(exist, false, sizeof(exist));
memset(pos, 0, sizeof(pos));
int start = 0;
int maxLen = 0;
for(int i=0; i<s.size(); i++)
{
int cur = s[i] - 'a';
if(exist[cur])
{
for(int j=start; j<=pos[cur]; j++)
exist[s[j]-'a'] = false;
start = pos[cur] + 1;
exist[cur] = true;
pos[cur] = i;
}
else
{
exist[cur] = true;
pos[cur] = i;
maxLen = max(maxLen, i-start+1);
}
}
return maxLen;
}
};