1. 程式人生 > 實用技巧 >leetcode73:minmum-window-substring

leetcode73:minmum-window-substring

題目描述

給出兩個字串S和T,要求在O(n)的時間複雜度內在S中找出最短的包含T中所有字元的子串。 例如: S="ADOBECODEBANC"
T="ABC" 找出的最短子串為"BANC". 注意: 如果S中沒有包含T中所有字元的子串,返回空字串 “”;
滿足條件的子串可能有很多,但是題目保證滿足條件的最短的子串唯一。
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.

示例1

輸入

複製
"ADOBECODEBANC","ABC"

輸出

複製
"BANC"

連結:https://www.nowcoder.com/questionTerminal/c466d480d20c4c7c9d322d12ca7955ac?f=discussion
來源:牛客網

class Solution { public: //維持一個視窗滑動,左邊是left,右邊是right,然後判斷是否包含T string minWindow(string S, string T) { string result; if(!S.size() || !T.size()) { return result; } map<char, int>Tmap; //儲存T字串裡字元,便於與S匹配
int left = 0; //左邊視窗,起始為0 int count = 0; //計數器,對視窗內T串字元數量進行計數,起始為0 //裝載T串 int minlen = S.size() + 1; //最小視窗,便於比較最後取最小的,初始化取最大 for(int i = 0; i < T.size(); ++i) { Tmap[T[i]]++; } //移動右邊視窗 for(int right = 0; right < S.size(); ++right) { if(Tmap.find(S[right]) != Tmap.end()) //當視窗內部有T中的字元 { if(Tmap[S[right]] > 0) { count++; //計數器+1 } Tmap[S[right]]--; //去掉包含的,剩下都是沒包含的 while(count == T.size())//當視窗內有T的所有字元,就要開始移動左視窗啦 { if(Tmap.find(S[left]) != Tmap.end()) { //好了,這就是一個包含字串的視窗範圍:left ~ right, //判斷是否比當前視窗還小,是就取串 if(minlen > right - left + 1) { //更新視窗大小 minlen = right -left + 1; result = S.substr(left, right - left + 1); } //捨棄視窗左邊字串,繼續移動視窗 Tmap[S[left]]++; if(Tmap[S[left]] > 0) //如果左邊連續相同,則count不遞減,視窗需要繼續向右移動 { count--; } } left++; //移動左視窗 } } } return result; } };