模板
//外层循环扩展右边界,内层循环扩展左边界
for (int l = 0, r = 0 ; r < n ; r++)
{
//当前考虑的元素
while (l <= r && check())
{
//区间[left,right]不符合题意
//扩展左边界
}
//区间[left,right]符合题意,统计相关信息
}
3. 无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是"abc",所以其长度为 3。
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
unordered_set<char> sets;
int i = 0;
int res = 0;
for (int j = 0; j < s.size(); j++)
{
while (i < j && sets.count(s[j]) != 0)
{
sets.erase(s[i++]);
}
sets.insert(s[j]);
res = max(res, j - i + 1);
}
return res;
}
};

Leave a comment