原题如下:
最长无重复字符的子串
给定一个字符串,请找出其中无重复字符的最长子字符串。
例如,在"abcabcbb"
中,其无重复字符的最长子字符串是"abc"
,其长度为 3
。
对于,"bbbbb"
,其无重复字符的最长子字符串为"b"
,长度为1
。
1、首先想到的办法就是,双层循环来做,遍历每一个字符,从该字符开始往后的字符计数,直到遇到重复的字符停止,该方法复杂度较高;
2、改进方法:使用两个函数,写一个计算字符串的最长前缀子串的函数,再用一层循环进行遍历,从当前字符直到末尾求其最长前缀子串的值,最大的即为所求的无重复字符的最长子字符串。
具体的c++代码如下:
int lengthOfLongestSubstring(string s) {
// write your code here
int l = s.size();
if (l == 0)
{
return 0;
}
int i, j;
int res = 0;
for (i = 0; i<l; i++)
{
int hash[200];
memset(hash, 0, sizeof(hash));
hash[s[i]]++;
for (j = i + 1; j<l; j++)
{
if (hash[s[j]] == 0)
{
hash[s[j]]++;
}
else
{
break;
}
}
if (j - i>res)
{
res = j - i;
}
}
return res;
}//双层循环做法
用最长前缀字符串来求:
int maxbefore(const string &s)//最长无重复前缀子串长度
{
int hash[200];
int i = 0;
int count = 0;
memset(hash, 0, sizeof(hash));
while (i<s.size()&&!hash[s[i]])
{
hash[s[i]]++;
i++;
count++;
}
return count;
}
int lengthOfLongestSubstring(string &s)
{
int l = s.size();
int i;
int res = 0;
for (i = 0; i < l; i++)
{
if (maxbefore(s.substr(i))>res)
{
res = maxbefore(s.substr(i));
}
}
return res;
}