Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.
Example 4:
Input: s = “”
Output: 0
Constraints:
0 <= s.length <= 5 * 104
思路:Example:
0 1 2 3 4 5
a b c d a b
i j!<i,max=i-j+1=1;
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i j!<i,i=1,p=0,max=i-p+1=2;
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i j!<i,i=2,p=0,max=i-p+1=3;
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i j!<i,i=3,p=0,max=i-p+1=4;
j
a b c d a b
i s[i]==s[j],i=4,p=j+1=1;break;max=i-p+1=4;
j
a b c d a b
i s[i]!=s[j]
j
a b c d a b
i s[i]==s[j],i=5,p=j+1=2;break;max=i-p+1=4;
j
*/
#include <iostream>
using namespace std;
int lengthOfLongestSubstring(string s){
int n=s.size(),i,j;
int max=0;
int p=0;
for(i=0;i<n;i++){
for(j=p;j<i;j++){
if(s[i]==s[j]){ //当s[i]==s[j]时,则将从p下标再重新开始寻找
p=j+1;
break;
}
}
if(i-p+1>max)max=i-p+1; //最大子串长度
}
return max;
}
int main(){
string s="abcbcdef";
int f=lengthOfLongestSubstring(s);
cout<<f;
system("pause");
return 0;
}