1. 程式人生 > >【LeetCode】76. Minimum Window Substring(C++)

【LeetCode】76. Minimum Window Substring(C++)

地址:https://leetcode.com/problems/minimum-window-substring/

題目:

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 )

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

實現:

使用滑動視窗的思想。
初始用一個map記錄T出現的字元的次數。
若S的當前字元在T中,就從map中把計數減一。
counter大於0說明當前子串中沒有完全包含T中的字串。
需要注意的是,如果要縮小滑動窗的大小,只需要當子串已經不能包含T的時候,再修改counter即可。當map的value等於0的時候,此時加1大於0,就說明視窗已經不能包含T了。
最開始把counter初始化為T.size()也比較巧妙,其實到最後,counter最多也就是1。

class Solution {
public:
	string minWindow
(string s, string t) { unordered_map<char, int> map; for (auto c : t) map[c]++; int counter = t.size(), l = 0, r = 0, d = INT_MAX, head = 0; while (r < s.length()) { char rc = s[r++]; if (map.count(rc)) { if (map[rc]-- > 0) counter--; } while (counter == 0) { if (r - l < d) d = r - (head = l); char lc = s[l++]; if (map.count(lc)) { if (map[lc]++ == 0) counter++; } } } return d == INT_MAX ? "" : s.substr(head, d); } };