leetcode -- 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 emtpy string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
[解题思路]
双指针问题,维护两个指针:start, end; 当start 和 end所围的字符串包含T时,此时将start尽可能往后移以寻找下一个window
本题一开始做不出来的问题在于如何移动start,即start移动的终止条件是什么?
line 27-28 是while循环的终止条件
1 public String minWindow(String S, String T) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if (S == null || T == null || S.length() == 0 || T.length() == 0) { 5 return ""; 6 } 7 int[] needToFind = new int[256]; 8 int[] hasFound = new int[256]; 9 10 for (int i = 0; i < T.length(); i++) { 11 needToFind[T.charAt(i)]++; 12 } 13 14 int minWinLen = Integer.MAX_VALUE; 15 int count = 0, tLen = T.length(); 16 int winBeg = 0, winEnd = 0; 17 for (int begin = 0, end = 0; end < S.length(); end++) { 18 if (needToFind[S.charAt(end)] == 0) { 19 continue; 20 } 21 hasFound[S.charAt(end)]++; 22 if(hasFound[S.charAt(end)] <= needToFind[S.charAt(end)]){ 23 count ++; 24 } 25 26 if(count == tLen){ 27 while(needToFind[S.charAt(begin)] == 0 || 28 hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]){ 29 if(hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]){ 30 hasFound[S.charAt(begin)]--; 31 } 32 begin ++; 33 } 34 35 int winLen = end - begin + 1; 36 if(winLen < minWinLen){ 37 winBeg = begin; 38 winEnd = end; 39 minWinLen = winLen; 40 } 41 } 42 } 43 44 if (count == T.length()) { 45 return S.substring(winBeg, winEnd + 1); 46 } 47 48 return ""; 49 }
ref
http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html