问题
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.
想法
用滑动窗口法,不断去寻找没有重复的字符串,并且用寻找到的字符串的长度跟已知的最大值比较,看是否要更新最大值。 至于如何比较高效地判断重复,则用hash表(26个字母作为关键字)
代码
int lengthOfLongestSubstring(char* str) {
if( str[ 0 ] == 0 )
{
return 0;
}
int app[ 128 ] = { 0 }, maxLen = 0;
for( int i = 0, j = 0; str[ j ] != '\0'; j++ )
{
i = app[ str[ j ] ] > i ? app[ str[ j ] ] : i;
maxLen = maxLen > j - i + 1 ? maxLen : j - i + 1;
app[ str[ j ] ] = j + 1;//这里变成j+1,一是避免跟初始化矛盾,二是跟上面的maxLen里的j-i+1取得统一形式
}
return maxLen;
}