您的位置:首页 > 职场人生

面试题:最长不含重复字符的子字符串

2018-02-02 12:21 351 查看
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含'a'~'z'的字符。例如,在字符串“arabcacfr”中,最长的不含重复字符的子字符串是“acfr”,长度为4。

思路:常规套路的话,先求有多少个子字符串,再看看是否有重复字符,那么一套下来就要O(n^3)。有点多,那么就用动态规划咯。

参考代码如下:

int longestSubstringWithoutDuplication(const std::string& str)

{

 int curLength=0;

int 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐