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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
class Solution { public: string minWindow(string s, string t) { unordered_map<char, int> tcnt; vector<int> matchS; string newS; int m = s.size(), n = t.size(); for (int i = 0; i < n; i++) tcnt[t[i]]++; for (int i = 0; i < m; i++) { if (tcnt.find(s[i]) != tcnt.end()) { newS += s[i]; matchS.push_back(i); } } int newSLength = newS.size(); int startIndex = 0, endIndex = 0; unordered_map<char, int> wcnt; int windowLength = 0; int newSize = INT32_MAX; string subStr; for (; endIndex < newSLength; endIndex++) { wcnt[newS[endIndex]]++; bool flag = true; for (auto it = tcnt.begin(); it != tcnt.end(); it++) { if (wcnt.find(it->first) == wcnt.end() || wcnt[it->first] < it->second) { flag = false; break; } } if (flag) { while (wcnt[newS[startIndex]] > tcnt[newS[startIndex]]) { wcnt[newS[startIndex]]--; startIndex++; } windowLength = matchS[endIndex] - matchS[startIndex] + 1; if (windowLength < newSize) { newSize = windowLength; subStr = s.substr(matchS[startIndex], windowLength); } wcnt[newS[startIndex]]--; if (wcnt[newS[startIndex]] == 0) wcnt.erase(wcnt[startIndex]); startIndex++; } } return subStr; } };
void slidingWindow(string s, string t) { Map<Character, Integer> need = new HashMap<>(); Map<Character, Integer> window = new HashMap<>(); for (char c : t.toCharArray()) need.put(c,need.getOrDefault(c,0)+1); int left = 0, right = 0; int valid = 0; while (right < s.size()) { char c = s.charAt(right); right++; ...
System.out.println("window: ["+left+","+ right+")"); while (window needs shrink) { char d = s[left]; left++; ... } } }
|