原题链接3. 无重复字符的最长子串 - 力扣(LeetCode)
思路,题目要求我们求给定字符串的最长无重复字符的子串,我们可以通过维护一个滑动窗口的形式来求解,
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
int l = 0, r = 0;
int res = 0;//可能是空字符
vector<int>m(256, 0);//使用一个大小为256的数组来存储字符的出现次数,ASCII码范围是0~255
while (r < n)
{
m[s[r]]++;
char w = s[r];
while (m[s[r]] > 1)
{
//如果出现重复,移动左指针,更新窗口,使其没有重复元素
m[s[l]]--;
l++;
}
res = max(res, r - l + 1);
r++;
}
return res;
}
};