[leetcode] 76.Minimum Window Substring

来源:互联网 发布:彩色macd指标源码 编辑:程序博客网 时间:2024/05/20 19:29

题目:
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 emtpy string “”.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
题意:
给定一个字符串S和一个字符串T。找出S中最小的窗口包含了S中所有的字符。
思路:
首先我们需要记录T中的字符,因为每个字符可能出现多次,所以我们需要记录该字符对应的个数。不妨使用256位的数组当做哈希表。统计T中每个字符出现的次数。然后,我们使用两个指针,初始化时第一个指针指向了S中的第一个元素,然后让第二个指针从第一个指针的位置开始往后扫描,直到找到能够了T中所有的字符,然后往后移动第一个指针来缩小这个窗口,截止条件是不能满足T中所有的字符出现的次数。此时继续往后移动第二个指针。一直到第二个指针移动到字符串末尾。
以上。
代码如下:

class Solution {public:    string minWindow(string s, string t) {        if (s.empty() || t.empty())return "";        int first = 0, second = 0;        int table[256];        for (int i = 0; i < 256; i++)table[i] = INT_MIN;        int un_meets = 0;        for (auto c : t) {            if (table[c] == INT_MIN) {                table[c] = 1;                un_meets++;            }            else                table[c]++;        }        int sLen = s.length();        int tLen = t.length();        int shortest = INT_MAX;        string result = "";        while (first < sLen && table[s[first]] == INT_MIN)first++;        second = first;        while (second < sLen) {            if (table[s[second]] != INT_MIN) {                table[s[second]]--;                if (table[s[second]] == 0)un_meets--;                while (un_meets == 0) {                    if (table[s[first]] != INT_MIN && second - first + 1 < shortest) {                        shortest = second - first + 1;                        result = s.substr(first, shortest);                        if (shortest == tLen)return result;                    }                    if (table[s[first]] != INT_MIN) {                        table[s[first]]++;                        if (table[s[first]] == 1)un_meets++;                    }                    first++;                }            }            second++;        }        return result;    }};
0 0
原创粉丝点击