剑指offer48-AcWing-61. 最长不含重复字符的子字符串
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
假设字符串中只包含从’a’到’z’的字符。
样例
输入:"abcabc"
输出:3
思路:
动态规划问题,设置f(i)表示以第i个字符结尾的最长子串的长度。分别用max_length、now_length记录最大字串的长度以及到以第i个位置上字符结尾的最长子串的长度。
然后分情况讨论:
一、若是第i个字符没有出现过
则 f(i) = f(i-1) + 1
二、若是第i个字符出现过,d表示第i位置上的字符与上一次出现的距离。
2.1 若是d > f(i-1) + 1,表示上次出现的i字符,不包含在现在的串中
因此 f(i) = f(i-1)+1
2.2若是d < f(i-1) + 1,表示上次出现的第i个位置的字符包含在现在的串中
因此f(i) = d
C++ code:
class Solution {
public:
int longestSubstringWithoutDuplication(string s) {
int n = s.size();
vector<int> position(26, -1);
int max_length = 0;
int now_length = 0;
for(int i = 0; i < n; i++){
int pre_position = position[s[i] - 'a'];
if(pre_position == -1 || i - pre_position > now_length){
now_length++;
if(now_length > max_length){
max_length = now_length;
}
}else{
now_length = i - pre_position;
}
position[s[i] - 'a'] = i;
}
return max_length;
}
};