Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty() || (0 == s.size()))
{
return 0;
}
char T[256] = {0};
char T1[256] = {0};
int mxl = 0;
int lastMxl = 0;
for (int i = 0; i < s.size(); i++)
{
int index = s[i];
if (T[index] > 0)
{
int pos = T[index];
for (int j = 0; j < mxl; j++)
{
int tmp = T[T1[j]] - pos;
T[T1[j]] = (tmp <= 0) ? 0 : tmp;
}
for (int j = 0; j < mxl; j++)
{
if ((pos + j) < 256)
{
T1[j] = T1[pos + j];
}
else
{
T1[j] = '\0';
}
}
if (mxl > lastMxl)
{
lastMxl = mxl;
}
mxl = mxl - pos;
}
T1[mxl++] = s[i];
T[index] = mxl;
}
return (mxl > lastMxl) ? mxl : lastMxl;
}
};