题解 | #最长不含重复字符的子字符串#
最长不含重复字符的子字符串
https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// write code here
// 双指针,难点在于啥时候更新两个指针的指向
map<char, int> m;
int res = 0;
for(int r = 0, l = 0; r < s.size(); ++r)
{
m[s[r]]++; // 记录元素出现次数
while (m[s[r]] > 1) { // 对于重复出现的元素,会一直更新左指向,目的把出现次数超过1的剔除
m[s[l++]]--; // 在移动左指针同时,把走过的的字符值也要跟着减少计数
}
res = max(res, r - l +1); // 当前位置更新长度最大值
}
return res;
}
};
挤挤刷刷! 文章被收录于专栏
记录coding过程

查看1道真题和解析