[leetcode] 76. Minimum Window Substring 解题报告

来源:互联网 发布:网络问卷调查技巧 编辑:程序博客网 时间:2024/05/20 18:20

题目链接: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).

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.


思路:思路很简单,就是遍历数组,先把所有的T中的字符找到,然后从左端缩减这个字符串,直到不能完全包含T.但是实现起来还是需要一些技巧.因为时间复杂度限制在了O(n),所以需要在O(1)的时间内判断是不是找到了所有的T中的字符.可以用一个hash表来计数所有字符出现的次数和一个标记num代表T总共有多少字符.

然后遍历S,并且将当前字符在hash表中计数减一,如果当前字符在hash表中计数是大于0的,说明这个字符是出现在T中的,将num也减一,代表我们找到了一个(这个num就是总共有多少字符,我们需要这个来标记是不是找完了所有字符,这也是能够在O(1)时间内判断当前窗口是不是覆盖了T的关键).这样当总的数量为0的时候我们就找到了一个覆盖T的子串窗口.这个窗口因为左端可能包含了一些不必要的字符,因此我们需要将窗口的左端向右移动,使其正好包含T.在窗口左端向右移动的过程中需要将碰到字符在hash表中+1,如果当前字符在hash表中的计数为0,而且我们又碰到了,说明这个字符是出现在T中的,因此num要加一.

代码如下:

class Solution {public:    string minWindow(string s, string t) {        unordered_map<char, int> hash;        int num = t.size(), len=INT_MAX, start =0, left = 0;        for(auto val: t) hash[val]++;        for(int i =0; i < s.size(); i++)        {            if(hash[s[i]]-- >0) num--;            while(num ==0)            {                len = (i-left+1)<len?(i-(start=left)+1):len;                if(hash[s[left++]]++ ==0) num++;            }        }        return len==INT_MAX?"":s.substr(start, len);    }};







0 0
原创粉丝点击