题目
- 给一个字符串,返回无重复字符的最长子串
思路
- 两个指针,right 在字符串无重复字符串时,向后遍历
- 有重复字符串时,left 向后遍历,直到变成无重复字符串
- 记录这过程中子串长度的最大值
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
int ans = 1;
unordered_set<char> ch_set;
ch_set.insert(s[0]);
int l = 0;
for (int i = 1; i < s.size(); i++) {
while (l < i && ch_set.find(s[i]) != ch_set.end()) {
ch_set.erase(s[l]);
l++;
}
ans = max(ans, i - l + 1);
ch_set.insert(s[i]);
}
return ans;
}
};