题目链接
leetcode
题目描述
给你一个字符串 s 、一个字符串 t ,返回 s 中涵盖 t 所有字符的最小子串。
如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 。
C++ 代码
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
| #include <iostream> #include <string> #include <unordered_map> #include <vector> using namespace std;
class Solution { public: string minWindow(string s, string t) { unordered_map<char, int> need; for (const char& c : t) { need[c]++; }
unordered_map<char, int> window; int left = 0, right = 0; int valid = 0; int start = 0, length = INT_MAX;
while (right < s.size()) { char c = s[right++]; if (need.count(c)) { window[c]++; if (window[c] == need[c]) { valid++; } }
while (valid == need.size()) { if (right - left < length) { start = left; length = right - left; }
char d = s[left++]; if (need.count(d)) { if (window[d] == need[d]) { valid--; } window[d]--; } } }
return length == INT_MAX ? "" : s.substr(start, length); } };
int main() { Solution solution; vector<string> s_cases = { "ADOBECODEBANC", "a", "a" }; vector<string> t_cases = { "ABC", "a", "aa" }; for (int i = 0; i < s_cases.size(); i++) { string s = s_cases[i]; string t = t_cases[i]; string result = solution.minWindow(s, t);
cout << "Input: s = \"" << s << "\", t = \"" << t << "\"" << endl; cout << "Output: " << (result.empty() ? "" : result) << endl; } return 0; }
|