1.题意
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
2. 思路
这题应该没有好说的就是不重复最长子串,可二位做或者一维做
法一暴力
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
int mp[256];
memset(mp, 0, sizeof(mp));
int num = 0, re = 0, index = 0;
for(int i = 0; i < n; i++){
if(mp[s[i]]){
index = max(index, mp[s[i]]);
// cout<<num<<" "<<i<<" "<<mp[s[i]]<<endl;
re = max(re, num), num = i - index + 1;
mp[s[i]] = i + 1;
// cout<<num<<" ";
continue;
}
num++, mp[s[i]] = i + 1;
}
re = max(re, num);
return re;
}
};
法二滑动窗口优化
言: cpp
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
int mp[256];
memset(mp, 0, sizeof(mp));
int num = 0, re = 0, index = 0;
for(int i = 0; i < n; i++){
if(mp[s[i]]){
index = max(index, mp[s[i]]);
// cout<<num<<" "<<i<<" "<<mp[s[i]]<<endl;
re = max(re, num), num = i - index + 1;
mp[s[i]] = i + 1;
// cout<<num<<" ";
continue;
}
num++, mp[s[i]] = i + 1;
}
re = max(re, num);
return re;
}
};