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,查找能够满足条件的窗体,然后挑选出最小的
java代码:
- public String minWindow(String S, String T) {
- int slen = S.length();
- int tlen = T.length();
- if(slen < tlen) return "";
- int[] need = new int[256];
- int[] reply = new int[256];
- for(int i=0;i<tlen;i++) {
- need[T.charAt(i)]++;
- }
- int i=0;
- int doing=0;
- int start = 0;
- int end = 0;
- String res="";
- int minLen = slen;
- while(i<slen) {
- if(doing < tlen) {
- if(reply[S.charAt(i)] < need[S.charAt(i)]) {
- reply[S.charAt(i)]++;
- doing++;
- } else {
- reply[S.charAt(i)]++;
- }
- i++;
- }
- if(doing == tlen) { //得到一个满足条件的窗体就进行判断
- end = i; //结束位置
- while(start < end && reply[S.charAt(start)] > need[S.charAt(start)]){
- reply[S.charAt(start)]--;
- start++;
- }
- if(end-start <= minLen) {
- minLen = end - start;
- res = S.substring(start,end);
- }
- reply[S.charAt(start)]--;
- start++;
- doing--;
- }
- }
- return res;
- }

浙公网安备 33010602011771号