题目:
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.
解题思想:
采用哈希函数,构造26个整数的数组,初始为0.如果字符第一次出现(对应数字值为0),将相应数组的值置1,并将此字符所在无重复字符子串长度加1。若此字符已出现(对应数字值为1),则向前寻找相同字符的下一个位置,从此位置重新开始计算(数组重置为0)。最后返回最长长度。
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int a[26];
int i=0,maxNO=0,sum=0,k;
memset(a,0,26*sizeof(int));
while(i<s.length())
{
if(a[s[i]-'a']==0)
{
a[s[i]-'a']=1;
sum++;
i++;
}
else
{
if(sum>maxNO)
maxNO=sum;
k=i;
while(s[--k]!=s[i]);
i=k+1;
sum=0;
memset(a,0,26*sizeof(int));
}
}
if(sum>maxNO)
maxNO=sum;
return maxNO;
}
};