题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
解题思路:O(n^2)的算法我不说了,敲了一版果断TLE,这里说说O(n)的;
1.首先i,j都从起始位置开始,j不断右移直到s[j]重复出现,此时情况如下左图所示;
2.如果是暴利O(n^2)的算法,会从i+1的位置重复上一步骤,但是我们会发现,从i+1作重复的步骤是没有意义的,因为它不管再长都会在j的位置出现重复,也就是说,其长度始终小于i~j的长度;
3.那么,i从哪一个位置开始才有意义的,答案是从C的那个位置处,也就是重复出现元素s[j]第一次出现位置的下一个,即下右图所示;
理解了整个过程,你会发现算法复杂度是O(n) + O(n) = O(n)的,每次j右移结束更新最大长度max即可;
参考代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i,j,ans;
i = j = ans = 0;
int len = s.size();
bool f[300];
memset(f,0,sizeof(f));
while(j<len){
if(!f[s[j]]){
f[s[j]] = 1;
j++;
}
else{
ans = max(ans,j-i);
while(s[i]!=s[j]){
f[s[i]] = 0;
i++;
}
i++;
j++;
}
}
ans = max(ans,len-i);//边界
return ans;
}
};