leetcode力扣刷题打卡
题目:3. 无重复字符的最长子串
描述:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
解题思路
1、用unordered_map来记录当前字符以及所在下标;
2、双指针;
3、如果当前字符在unordered_map中出现,删除左指针的键值对,左指针 + 1;
原代码##
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
unordered_map<char, int> map;
int l = 0, r = 0, ans = 0;
while (r < n) {
while (map.find(s[r]) != map.end()) {
map.erase(s[l]);
l++;
}
map[s[r]] = r;
ans = max(ans, r - l + 1);
r++;
}
return ans;
}
};