Minimum Window Substring

Source: Internet
Author: User

Given a string S and a string T, find the minimum window in S which would 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 so covers all characters in T, return the emtpy string "" .

If There is multiple such windows, you is guaranteed that there would always being only one unique minimum window in S.

Below we use S = "acbbaca" and T = "aba" to demonstrate this algorithm. The basic idea is to use two pointers (the Begin and end index of the legal window) and two table (needtofind and hasfound) in the process of traversing S,Needtofind Save the number of each letter in T (she: equivalent to our Needtofill),hasfound Save the number of each letter currently collected. We also use a count variable to hold the total number of letters currently collected, but the number of letters collected is not counted in count . In this case, when Count equals T.length, then we know that a legitimate window is encountered.

We use the end pointer to traverse S, assuming that the current end points to the letter x in S, if X is the letter in T, Hasfound[x] plus one. If HASFOUND[X] is currently less than or equal to Needtofind[x] (she: note that the letter X has not been collected or just collected), then we also added count. When the condition of the legal window is satisfied, that is, Count equals t.length, we immediately increment the begin pointer and ensure that count equals t.length is always incremented.

In the process of incrementing the begin pointer, how can we guarantee that " always count equals T.length"?

Assuming that begin points to the letter x, if hasfound[x] is greater than needtofind[x],hasfound[x] subtracts one and increments begin. (She: There's a lot of picture here.) Because the currently encountered X is a redundant left-hand letter, here the operation is actually equivalent to the previous two algorithms in the "delete the corresponding letter in the charappearancerecorder of the linked list head node", a bit like a lazy to heavy, One is eager to heavy) otherwise, the current begin is the start index of the window.

Next we can get the length of the current window through End-begin + 1. The minimum window length can be updated here.

The algorithm actually finds the first valid window first, and then maintains the legitimacy of the window during the next scan (she: count is always less than or equal (when encountering a new window) t.length).

Look at the graph below.

i) S  = " Acbbaca " and T  = " ABA ".

II) Find the first legal window. Note here that we cannot increment the begin pointer because hasfound[' a '] equals needtofind[' A ', which is 2. If we increment begin at this point, it is not a legitimate window.

III) Find a second legal window. The begin pointer points to the first a,hasfound[' a '] equals 3, while needtofind[' a ' is equal to 2, indicating that a is a redundant a, we decrement hasfound[' a '] and increment begin.

IV) We also need to skip the letters that are not in T, such as the C above. Now beging points to B,hasfound[' B '] equals 2, greater than needtofind[' B '], indicating that this is also a redundant B, we decrement hasfound[' a '] and increment begin.

V) begin to point to B, when hasfound[' B '] equals needtofind[' B '. Can no longer be reduced, and the begin cannot be moved again, here is the starting position of a short window.

Begin and end go forward at most n times, and the entire algorithm executes less than 2N. The degree of complexity is O (N).

Class Solution {Private:int count1[256];        int count2[256];p ublic:string Minwindow (String S, String T) {//Start typing your C + + solution below Do not write int main () function if (t.size () = = 0 | |                    S.size () = = 0) return "";        memset (count1, 0, sizeof (COUNT1));                memset (count2, 0, sizeof (COUNT2));            for (int i = 0; i < t.size (); i++) {count1[t[i]]++;        count2[t[i]]++;                } int count = T.size ();        int start = 0;        int minSize = Int_max;        int Minstart; for (int end = 0; end < S.size (); end++) {if (Count2[s[end]] > 0) {coun                t1[s[end]]--;            if (Count1[s[end]] >= 0) count--; } if (count = = 0) {while (true) {if (c Ount2[s[start]] > 0) {                        if (Count1[s[start]] < 0) count1[s[start]]++;                    else break;                } start++;  } if (MinSize > End-start + 1) {minSize = End-start +                    1;                Minstart = start;                }}} if (minSize = = Int_max) return "";                string ret (S, Minstart, minSize);            return ret; }};

Minimum Window Substring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.