Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
题意
给出两个字符串s和t,要求s中的一个最短子串使得这个子串能覆盖t中所有的字符,如果不存在就输出空字符串
题面其实挺坑的,因为覆盖t中所有的字符意思是,如果t中出现重复字符则输出子串中相应字符的出现次数要大于等于t中的。
这种文字游戏就很没意思了,我一开始按t中字符只要s中出现就算是覆盖的,很坑
题解
1 class Solution { 2 public: 3 string minWindow(string s, string t) { 4 int p1 = 0, p2 = -1, l1 = s.length(), l2 = t.length(), kind = 0; 5 vector<int>mark(256, 0); 6 vector<int>count(256, 0); 7 for (int i = 0; i < l2; i++) { 8 mark[t[i]]++; 9 kind++; 10 } 11 int S = -1, E = -1, countkind = 0, minl = INT_MAX; 12 while (p2 < l1 - 1) { 13 if (mark[s[p2 + 1]]) { 14 if (count[s[p2 + 1]] < mark[s[p2 + 1]])countkind++; 15 count[s[p2 + 1]]++; 16 } 17 while (p1 < p2 + 1 && (mark[s[p1]] == 0 || count[s[p1]] > mark[s[p1]])) { 18 if (mark[s[p1]])count[s[p1]]--; 19 p1++; 20 } 21 if (kind == countkind && (p2 - p1 + 1) < minl) { 22 minl = p2 - p1 + 2; 23 S = p1, E = p2; 24 } 25 p2++; 26 } 27 if (S == -1)return ""; 28 return s.substr(S, minl); 29 } 30 };
一道略微复杂的滑动窗口题,想明白了写不难
这道题蛮神奇的,第一次memory usage beat了100%,不知道这到底咋算的