lintcode32 最小子串覆蓋

1、t[256] 記錄 target字符串每個(gè)字符出現(xiàn)的次數(shù);
2、int start, i;
i首先遍歷source,遍歷到從 start 到 i 的子串包含 target ;是否包含根據(jù)兩個(gè)數(shù)組間的值來判斷找到的字符數(shù)量,來判斷是否包含。
然后從start開始遍歷,去除無用的字符。
用變量begin、end保存當(dāng)前start 到 i的字符串。

start后移一位,此時(shí)一定不滿足包含條件,再后移 i 找到新的符合條件的字符串。
參考:https://blog.csdn.net/u012156116/article/details/80648698

class Solution {
public:
   /**
    * @param source : A string
    * @param target: A string
    * @return: A string denote the minimum window, return "" if there is no such a string
    */
   string minWindow(string &source , string &target) {
       // write your code here
       int *t = new int[256]();
       
       for(int i = 0;i < target.length();i++){
           t[target[i]]++;
       }
       
       int *s = new int[256]();
       int found = 0;                    //找到的字符數(shù)量
       int start = 0;
       int begin = 1,end = 0;
       int len  = source.length()+1;
       
       for(int i = 0;i < source.length();i++){
           s[source[i]]++;
           if(s[source[i]] <= t[source[i]]) //target中沒有的為0,存在的話,source取到一次就加1。
           {
               found++;
           }
           if(found == target.length()){
               while(start < i && s[source[start]] > t[source[start]]){
                   s[source[start]]--;
                   start++;
               }                         //去除前面多余的字符
               
               if(i-start+1 < len){
                   begin = start;
                   end  = i;
                   len = i - start + 1;
               }
               start++;                  //將start后移 尋找其他子串
               found--;                  //后移后 肯定不再滿足條件
           }
       }
       if(begin > end){
           return "";                    //對應(yīng)一個(gè)子串也沒找到的情況
       }
       string res = source.substr(begin,end-begin+1);
       return res;
   }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容