题目: 请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含‘a’-‘z’的字符。
解题思路: 我么们可以用动态规划的方法来进行思考。首先定义函数f(i)表示以第i个字符为结尾的不包含重复字符的子字符串的最长长度。我们从左到右逐一扫描字符串中的每个字符。当我们计算以第i个字符为结尾的不包含重复字符的子字符串的最长长度f(i)时,我们已经得到f(i-1)了。
如果第i个字符之前没有出现过,那么f(i) = f(i-1) + 1。如果第i个字符之前已经出现过,那我们就要先计算第i个字符和它上次出现在字符串中的位置的距离,并记为d,接着分两种情形分析。第一种情形是d小于或者等于f(i-1),此时第i个字符上次出现在f(i-1)对应的最长子字符串之中,所以f(i) = d。第二种情况是d大于f(i-1),此时第i个字符上次出现在f(i-1)对应的最长子字符串之前,所以f(i) = f(i-1) + 1。
接下来我们用C++来进行编程:
int longestSubstringWithoutDuplication(const std::string& str)
{
int curLength = 0;
int maxLength = 0;
int* position = new int[26];
for(int i = 0; i < str.length(); ++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;
}