[LeetCode] 76. Minimum Window Substring

[LeetCode] 76. 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).

For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.

Note:
If there is no such window in S that covers all characters in T, return the empty string “”.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.


要求在O(n)時間複雜度內,找出S字符串中包含T中所有字符的最短子字符串。
思路: 實在想不到。。。
參考並膜拜了超級大神的代碼

定義一個長度128(char的長度)的數組map,記錄T中的字符和出現次數;同時初始化一個計數器cnt=T.length。
然後第一個指針end開始遍歷S,遇到對出現的字符都在數組中-1計數,當遇到在T中的字符總計數器同時也-1,可以知道當cnt==0時,第一個匹配的S的子字符串已經出現了,這時另一個指針begin也開始遍歷S,遇到對出現的字符都在數組中+1計數,當遇到T中的字符,總計數器+1,直到cnt!=0時又回到end指針,如此類推。


class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> ht(128, 0); // 整個char位的長度
        int cnt = t.length();
        int begin=0, end=0, min_len=INT_MAX, head=0;
        for (int i=0; i<cnt; ++i) {
            ++ht[t[i]];
        }
        while (end < s.length()) {
            if (ht[s[end]] > 0) --cnt;
            --ht[s[end]];
            ++end;
            while (cnt == 0) {
                if (min_len > end-begin) {
                    min_len = end-begin;
                    head = begin;
                }

                if (ht[s[begin]] == 0) ++cnt;
                ++ht[s[begin]];
                ++begin;
            }
        }
        return min_len == INT_MAX ? "" : s.substr(head, min_len);
    }
};
發佈了35 篇原創文章 · 獲贊 0 · 訪問量 4060
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章