描述
给出一个字符串,求出不包含重复字符的最长字串
解决
从头至尾遍历,记录最长长度,利用map做标记。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> cnt;
int l = 0, r = 0;
int max_lenth = 0;
int lenth = s.size(), t = 0;
while (l < lenth && r < lenth){
if (l == r || cnt[s[r]] == 0){
++t;
cnt[s[r]] = 1;
}else if (cnt[s[r]] == 1){
cnt[s[r]] = 0;
max_lenth = max_lenth > t ? max_lenth : t;
while (s[l] != s[r]){
cnt[s[l]] = 0;
++l;
}
++l;
t = r - l;
continue;
}
++r;
}
//cout << "t = " << t << endl;
return max_lenth > t ? max_lenth : t;
}
};
讨论区看到的方法
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0, len = 0;
if(!s.size())
return ans;
vector<bool> vis(300, false);
for(int i = 0, j = 0; j < s.size(); ){
if(!vis[(int)s[j]]){
vis[(int)s[j] ] = 1;
++ j;
++ len;
}else{
vis[(int)s[i]] = 0;
-- len;
++ i;
}
ans = max(ans, len);
}
return ans;
}
};