动态规划-最长不含重复字符的子字符串

// 面试题48:最长不含重复字符的子字符串
// 题目:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子
// 字符串的长度。假设字符串中只包含从'a'到'z'的字符。

#include <string>
#include <iostream>
动态规划
int longestSubstringWithoutDuplication_2(const std::string& str)
{
    int curLength = 0;//记录当前长度
    int maxLength = 0;//记录最大长度

    int* position = new int[26];//检测26个字母上次出现在字符串下标,没有用过为-1
    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;//记录这个字符的位置为i
    }

    if (curLength > maxLength)//记录到结束了,要比较一下最后一段的长度是否是最长的
        maxLength = curLength;

    delete[] position;
    return maxLength;
}
原文地址:https://www.cnblogs.com/cgy1012/p/11492998.html