题目描述:
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含’a’~'z’的字符。
输入描述:
输入的第一行为一个字符串
输出描述:
输出一个整数表示最长不含重复子字符串的长度
#include<iostream>
#include<string.h>
using namespace std;
int longestSubLength(string input);
int main()
{
string input;
cin>>input;
int result=longestSubLength(input);
printf("%d",result);
}
int longestSubLength(string input)
{
/**
* subLength用于统计当前子串长度
* maxLength用于统计最长子串长度
*/
int subLength=0,maxLength=0,arr[26],strLength=input.length();
memset(arr,-1,sizeof(arr)); //存放当前字符出现的最新位置
for(int index=0;index<strLength;index++){
int preIndex=arr[input[index]-'a'];
if(preIndex<0||index-preIndex>subLength){ //当该字符从未出现或者上一次出现位置大于当前子串长度说明该子串长度加一
subLength++;
}else{
if(subLength>maxLength){
maxLength=subLength;
}
subLength=index-preIndex;
}
arr[input[index]-'a']=index; //更新字符最新位置
}
if(subLength>maxLength){ //更新最后一个子串的长度
maxLength=subLength;
}
return maxLength;
}