题目描述:
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从’a’到’z’的字符。
分析:
完整代码:
//输入数组的 string 常引用,输出满足条件的子字符串长度
int longestSubstringWithoutDuplication(const string& str)
{
//声明一个变量,表示当前以 i 为结尾的字符的字符串长度
int Currentlength = 0;
//声明一个变量,表示满足条件的字符串的长度
int Maxlength = 0;
//声明一个数组,用来存放 26 个字母在字符串 中出现的位置
int position = new int[26];
//初始化 position数组
for(int i = 0; i < 26; ++i)
{
position[i] = -1;
}
//遍历整个字符串
for(int i = 0; i < str.length; ++i)
{
//声明一个变量,用来指示当前 i 号位置对应的字符上一次在字符串中出现的位置
int preIndex = position[str[i] - 'a'];
//如果当前 i 号对应的字符在之前没有出现或者字符出现过但是不在 CurrentLength 中
if(preIndex < 0 || i - preIndex >CurrentLength)
{
CurrentLength++;
}
//如果当前 i 号对应的字符出现在 CurentLength 中
else
{
//如果 CurrentLength > Maxlength
if(CurrentLength > Maxlength)
//更新MaxLength
Maxlength = CurrentLength;
//重新计算 CurrentLength
CurrentLength = i - preIndex;
}
//将当前 i 号对应的字符在字符串中出现的位置存储到 position
position[str[i] - 'a'] = i;
}
//如果 CurentLength > Maxlength
if(CurentLength > Maxlength)
Maxlength = CurentLength;
//删除 position数组
delete []positon;
//返回最终的字符长度
return Maxlength;
}