Minimum Window Substring leetcode java


題目

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.

 

題解:

這道題也是用滑動窗口的思想,思想跟 Substring with Concatenation of All Words是一樣的,同樣是利用HashMap來存Dict,然后來遍歷整個母串。因為這里是要求最短的包含子串的字符串,所以中間是可以允許有非子串字符的,當遇見非子串字符而count又沒到子串長度時,可以繼續走。

當count達到子串長度,說明之前遍歷的這些有符合條件的串,用一個pre指針幫忙找,pre指針幫忙找第一個在HashMap中存過的,並且找到后給計數加1后的總計數是大於0的,判斷是否為全局最小長度,如果是,更新返回字符串res,更新最小長度,如果不是,繼續找。

這道題的代碼也參考了code ganker的。

 

代碼如下:

 

 1  public String minWindow(String S, String T) {
 2     String res = "";
 3      if(S ==  null || T ==  null || S.length()==0 || T.length()==0)
 4          return res;
 5     
 6     HashMap<Character, Integer> dict =  new HashMap<Character, Integer>();
 7      for( int i =0;i < T.length(); i++){
 8          if(!dict.containsKey(T.charAt(i)))
 9             dict.put(T.charAt(i), 1);
10          else
11             dict.put(T.charAt(i), dict.get(T.charAt(i))+1);
12     }
13     
14      int count = 0;
15      int pre = 0;
16      int minLen = S.length()+1;
17      for( int i=0;i<S.length();i++){
18          if(dict.containsKey(S.charAt(i))){
19             dict.put(S.charAt(i),dict.get(S.charAt(i))-1);
20              if(dict.get(S.charAt(i)) >= 0)
21                 count++;
22                 
23              while(count == T.length()){
24                  if(dict.containsKey(S.charAt(pre))){
25                     dict.put(S.charAt(pre),dict.get(S.charAt(pre))+1);
26                     
27                      if(dict.get(S.charAt(pre))>0){
28                          if(minLen>i-pre+1){
29                             res = S.substring(pre,i+1);
30                             minLen = i-pre+1;
31                         }
32                         count--;
33                     }
34                 }
35                 pre++;
36             }
37         } // end for if(dict.containsKey(S.charAt(i)))
38      }
39      return res;
40 }

Reference:

 http://blog.csdn.net/linhuanmars/article/details/20343903

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM