面试题48:最长不含重复字符的子字符串
题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从’a’到’z’的字符。例如,在字符串"arabcacfr"中,最长的不含重复字符的子字符串是"acfr",长度为4。
分析思路:
- 我们可以使用蛮力的方法,但是效率极低。我们可以采用动态规划算法来提高效率。首先定义函数 f(i) 表示以第 i 个字符为结尾的不包含重复字符的子字符串的最长长度。我们从左到右逐一扫描字符串中的每个字符。
- 如果第 i 个字符之前没有出现过,那么 f(i)=f(i-1)+1。
- 如果第 i 个字符之前已经出现过,那情况就要复杂一点了。我们先计算第 i 个字符和它上次出现在字符串中的位置的距离,并记为d,接着分两种情形分析:1、d<=f(i-1),则f(i)=d;2、d>f(i-1),则f(i)=f(i-1)+1
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<cmath>
using namespace std;
int longestSubstringWithoutDuplication(const string& str){
int curLength=0, maxLength=0;
int* position=new int[26];
for(int i=0;i<26;i++) position[i]=-1;
for(int i=0;i<str.length();i++){
int prevIndex=position[str[i]-'a'];
if(prevIndex<0 || i-prevIndex>curLength) curLength++;
else{
if(curLength>maxLength) maxLength=curLength;
curLength=i-prevIndex;
}
position[str[i]-'a']=i;
}
if(curLength>maxLength) maxLength=curLength;
delete[] position;
return maxLength;
}
int main() {
printf("%d", longestSubstringWithoutDuplication("arabcacfr"));
return 0;
}