//遍历 O(N2)
int findMax(const string& strsrc)
{
int ret = 0;
int cTemp[256] = {0};
for(int i=0; i < strsrc.length(); ++i)
{
int mid_ret = 0;
memset(cTemp, 0, sizeof(cTemp));
cTemp[strsrc[i]] = 1;
for(int j =i+1;j<strsrc.length(); ++j)
{
if(cTemp[strsrc[j]] != 0)
{
mid_ret = j-i;
break;
}
else
{
cTemp[strsrc[j]] = 1;
}
}
ret = max(mid_ret, ret);
}
return ret;
}
//优化后,用字典保存出现过的字符 o(n)
int findMax2(const string& strsrc)
{
int l=0,r=0;
int ret = 0;
int cTemp[256] = {0};
cTemp[strsrc[0]] = 1;
for(r=1; r <strsrc.length(); ++r)
{
cTemp[strsrc[r]] += 1;
while(cTemp[strsrc[r]] > 1)
{
cTemp[strsrc[l]] -= 1;
l += 1;
}
ret = max(ret, r-l+1);
}
return ret;
}
//进一步优化,去掉while循环,保存字符出现过的位置 o(n)
int findMax3(const string& strsrc)
{
int l=0,r=0;
int ret = 0;
int cTemp[256] = {-1};
cTemp[strsrc[0]] = 0;
for(r=1; r <strsrc.length(); ++r)
{
if(cTemp[strsrc[r]] >=0 && cTemp[strsrc[r]] >=l)
{
l = cTemp[strsrc[r]] + 1;
}
cTemp[strsrc[r]] = r;
ret = max(ret, r-l+1);
}
return ret;
}
int main()
{
string strsrc = "abcabcabc";
int ret = findMax3(strsrc);
printf("ret = %d\n", ret);
return 0;
}