0%
滑动窗口
1.什么是滑动窗口
1)滑动窗口是一个队列,
2)先移动右指针,
3)当满足条件时,移动左指针,直到不满足条件,
4)重复2,3步,直到右指针到末位。
leetcode 3.无重复字符的最长子串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int lengthOfLongestSubstring(string s) { if(s.size() == 0) return 0; unordered_set<char> lookup; int maxStr = 0; int left = 0; for(int i = 0; i < s.size(); i++){ while (lookup.find(s[i]) != lookup.end()){ lookup.erase(s[left]); left ++; } maxStr = max(maxStr,i-left+1); lookup.insert(s[i]); } return maxStr; } };
|
leetcode 76. 最小覆盖子串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public: string minWindow(string s, string t) { int start=0,minlen=INT_MAX,left=0,right=0; unordered_map<char,int> window; unordered_map<char,int> need; for(char c:t) need[c]++; int match=0; while(right<s.size()) { char c1=s[right]; if(need.count(c1)) { window[c1]++; if(window[c1]==need[c1]) { match++; } } right++; while(match==need.size()) { if(right-left<minlen) { start=left; minlen=right-left; } char c2=s[left]; if(need.count(c2)) { window[c2]--; if(window[c2]<need[c2]) match--; } left++; } } return minlen == INT_MAX ? "" : s.substr(start, minlen); } };
|