
题目:
类型:滑动窗口
题解:
利用滑动窗口,窗口内(开一个集合或者其他存储结构)符合条件时,窗口右边 向右移动(扩大窗口),不符合条件时,窗口左边向右移动(缩小窗口)。
在官方题解看到了一个写的非常棒的滑动窗口模版!
//外层循环扩展右边界,内层循环扩展左边界
for (int l = 0, r = 0 ; r < n ; r++) {
//当前考虑的元素
//区间[left,right]不符合题意
while (l <= r && check()) {
//扩展左边界
}
//区间[left,right]符合题意,统计相关信息
}本题题解:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char>st;
int n = s.size();
int ans = 0;
for(int l = 0, r = 0; r < n; r ++){
char ch = s[r];
while(st.count(ch)){
st.erase(s[l]);
l ++;
}
st.insert(s[r]);
int tmp_ans = st.size();
ans = max(tmp_ans, ans);
}
return ans;
}
};官方题解: