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.
解析:
(1)先将所有的res[0:length-1],置为1,因为每个子串最小长度为1.
(2)一般的想法是针对每一个位置i,向左或者向右寻找与s[i]不同的子串
但是对于abca这个串,0,1,2位置上最长字串都为3。这里我们选择计算最后一个位置上的最长字串
即:位置0 对应a,位置1对应ab,位置2对应abc,只向前搜索。
#include <iostream>
#include <string>
using namespace std;
int lengthOfLongestSubstring(string s) {
int length = s.length();
if(length == 0)
return 0;
int *res = (int *)malloc(sizeof(int)*length);
int max;
max = res[0]=1;
for(int i=1;i<length;i++)
{
res[i] = 1;
int k;
for(k=1;k<=res[i-1];k++)
{
if(s[i] == s[i-k])
break;
else
res[i] = res[i]+1;
}
if(max < res[i])
max = res[i];
}
return max;
}
int main(void)
{
// string s = "abcabcbb";
// string s = "wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco";
string s = "bbbbbb";
int res = lengthOfLongestSubstring(s);
cout << res << endl;
system("pause");
return 0;
}