Minimum Window Substring

来源:互联网 发布:农村淘宝发展前景分析 编辑:程序博客网 时间:2024/05/01 09:55

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


思路:怎么说呢,我们定义一个数组count_Have[MAY_APPEAR_ASCII_COUNT=58]={0},里面储存了T每个字符的出现次数,然后开始拉伸窗口末端,使这个字符数组count_Have里每一个元素都小于等于0,则此时窗口已经包括了所有T中的字符,接着我们收紧窗口前端,一直收到count_Have里出现大于0的元素为止,则上一个位置是这次窗口的最小起点,我们把这个窗口长度与上次得到的minLength比较,保留更小的那个。就这么一直搜索,直到搜索结束。

伪代码:不怎么会写,后面再发把。

具体代码:

<span style="font-size:14px;">string minWindow(string s, string t) {    int lenS = s.length();    int lenT = t.length();    if ((lenS == 0) || (lenT == 0))    {        return "";    }    int resultStart = 0, resultEnd = 0, minLength = lenS, unSatisfyCount = 0;    bool found = false, reachEnd = false;    int countHave[58] = { 0 };    for (int i = 0; i < lenT; i++)    {        countHave[t[i] - 'A']++;    }    for (int i = 0; i < 58; i++)    {        if (countHave[i]>0)        {            unSatisfyCount++;        }    }    //初始化部分    int pointStart = 0, pointEnd = 0;    while (!reachEnd)    {        reachEnd = true;        for (; pointEnd < lenS; pointEnd++)        {            countHave[s[pointEnd] - 'A']--;            if (countHave[s[pointEnd] - 'A'] == 0)            {                unSatisfyCount--;                if (unSatisfyCount == 0)                {                    found = true;                    reachEnd = false;                    break;                }            }        }        for (; pointStart <= (lenS - lenT); pointStart++)        {            countHave[s[pointStart] - 'A']++;            if (countHave[s[pointStart] - 'A']>0)            {                unSatisfyCount++;                pointStart++;                pointEnd++;                break;            }        }        if ((!reachEnd) && ((pointEnd - pointStart+1)<minLength))        {            resultStart = pointStart-1;            resultEnd = pointEnd-1;            minLength = resultEnd - resultStart+1;        }    }    if (found)    {        return s.substr(resultStart, minLength);    }    return "";}</span>


0 0