Minimum Window Substring leetcode java

愛做飯的小瑩子發表於2014-07-28

題目

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

 

相關文章