题意
题解
方法一:滑动窗口
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<int> se;
int n = s.size();
int right = 0;
int ans = 0;
for (int left = 0; left < n; left++) {
if (left != 0) se.erase(s[left-1]);
while (right < n && !se.count(s[right])) {
se.insert(s[right]);
right++;
}
ans = max(ans, right - left);
}
return ans;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
set<char> charSet;
int n = s.size();
int res = 0;
int cnt = 0, i = 0, j = 0;
while (j < n) {
while(charSet.count(s[j]) == 0 && j < n) {
charSet.insert(s[j++]);
cnt++;
res = max(res, cnt);
}
while(charSet.count(s[j])) {
charSet.erase(s[i++]);
cnt--;
}
}
return res;
}
};