[LeetCode] 76. Minimum Window Substring

来源:互联网 发布:淘宝 正义哥 编辑:程序博客网 时间:2024/06/14 03:55

[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);    }};
0 0
原创粉丝点击