LeetCode-Longest Substring Without Repeating Characters-最长不重复子串-滑动窗口
https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
跟“Minimum Window Substring”差不多的一道题。如果往LCS方向思考就走弯路了。正解还是滑动窗口。维护一个到当前位置的最左边界以及一个set<char>,当遇到重复时就收缩左边界l直到不重复。记得更新res要在每次插入新元素时,否则会漏掉最后的一个不重复子串。
class Solution {
public:
int n,m;
int lengthOfLongestSubstring(string s) {
n=s.length();
int l=0;
int res=0;
unordered_set<char> st;
for(int i=0;i<n;i++){
char ch=s[i];
if (st.find(ch)!=st.end()){
while(st.find(ch)!=st.end()){
st.erase(s[l]);
l++;
}
}
st.insert(ch);
res=max(res,i-l+1);
}
return res;
}
};
浙公网安备 33010602011771号