76. Minimum Window Substring
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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
代码如下:
1 public class Solution { 2 public String minWindow(String s, String t) { 3 if(s==null||t==null||s.length()==0||t.length()==0) 4 return ""; 5 int[] c = new int[128]; 6 boolean[] flag = new boolean[128]; 7 for(int i = 0;i < t.length(); i++){ 8 flag[t.charAt(i)] = true; 9 ++c[t.charAt(i)]; 10 } 11 12 int count = 0,l = 0,minl = 0,minSize = s.length()+1; 13 14 for(int r = 0;r < s.length(); r++) 15 if(flag[s.charAt(r)]){ 16 if(--c[s.charAt(r)]>=0) 17 ++count; 18 while(count==t.length()){ 19 if(r-l+1<minSize){ 20 minl = l; 21 minSize = r-l+1; 22 } 23 24 if(flag[s.charAt(l)]&&(++c[s.charAt(l)])>0) 25 count--; 26 l++; 27 } 28 } 29 if(minSize>s.length()) 30 return ""; 31 return s.substring(minl,minl+minSize); 32 } 33 }
态度决定高度,细节决定成败,