最小覆盖字串(滑动窗口)
题目:给两个字符串,请你在S中找到包含T中全部字母的最短字串。
#include <iostream> #include <cstring> #include <algorithm> #include <unordered_map> using namespace std; string min_window(string s, string t) { unordered_map<char, int> need, window; for(char c: t) need[c]++; int left = 0, right = 0; int valid = 0; int start = 0, len = 0x3f3f3f3f; while(right < s.size()) { char c = s[right]; right++; if(need.count(c)) { window[c]++; if(window[c] == need[c]) valid++; } while(valid == need.size()) { if(right - left < len) { start = left; len = right - left; } char d = s[left]; left++; if(need.count(d)) { if(window[d] == need[d]) valid--; window[d]--; } } } return len == 0x3f3f3f3f? "": s.substr(start, len); } int main() { string s = "ADBECFEBBVANC"; string t = "BANC"; cout << min_window(s, t) << endl; return 0; }

浙公网安备 33010602011771号