|
| 1 | +/* |
| 2 | +Minimum Window Substring |
| 3 | +======================== |
| 4 | +
|
| 5 | +Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". |
| 6 | +
|
| 7 | +The testcases will be generated such that the answer is unique. |
| 8 | +
|
| 9 | +A substring is a contiguous sequence of characters within the string. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: s = "ADOBECODEBANC", t = "ABC" |
| 13 | +Output: "BANC" |
| 14 | +Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: s = "a", t = "a" |
| 18 | +Output: "a" |
| 19 | +Explanation: The entire string s is the minimum window. |
| 20 | +
|
| 21 | +Example 3: |
| 22 | +Input: s = "a", t = "aa" |
| 23 | +Output: "" |
| 24 | +Explanation: Both 'a's from t must be included in the window. |
| 25 | +Since the largest window of s only has one 'a', return empty string. |
| 26 | + |
| 27 | +Constraints: |
| 28 | +m == s.length |
| 29 | +n == t.length |
| 30 | +1 <= m, n <= 105 |
| 31 | +s and t consist of uppercase and lowercase English letters. |
| 32 | + |
| 33 | +Follow up: Could you find an algorithm that runs in O(m + n) time? |
| 34 | +*/ |
| 35 | + |
| 36 | +class Solution |
| 37 | +{ |
| 38 | +public: |
| 39 | + bool same(unordered_map<char, int> &sMap, unordered_map<char, int> &tMap) |
| 40 | + { |
| 41 | + for (auto &i : tMap) |
| 42 | + { |
| 43 | + if (sMap[i.first] < i.second) |
| 44 | + return false; |
| 45 | + } |
| 46 | + return true; |
| 47 | + } |
| 48 | + |
| 49 | + string minWindow(string s, string t) |
| 50 | + { |
| 51 | + int Size = s.size() + 1; |
| 52 | + int i = 0, j = 0; |
| 53 | + string ans, curr; |
| 54 | + |
| 55 | + unordered_map<char, int> tMap, sMap; |
| 56 | + for (auto &i : t) |
| 57 | + tMap[i]++; |
| 58 | + |
| 59 | + while (j < s.size()) |
| 60 | + { |
| 61 | + sMap[s[j]]++; |
| 62 | + j++; |
| 63 | + |
| 64 | + while (same(sMap, tMap)) |
| 65 | + { |
| 66 | + if (Size > j - i) |
| 67 | + { |
| 68 | + Size = j - i; |
| 69 | + ans = ""; |
| 70 | + for (int k = i; k < j; ++k) |
| 71 | + ans += s[k]; |
| 72 | + } |
| 73 | + sMap[s[i]]--; |
| 74 | + i++; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return ans; |
| 79 | + } |
| 80 | +}; |
0 commit comments