滑动窗口
1.什么是滑动窗口
滑动窗口是一个队列,
2)先移动右指针,
3)当满足条件时,移动左指针,直到不满足条件,
4)重复2,3步,直到右指针到末位。
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; } };
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); } };