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.

题意: 在O(n)的时间度里实现找到这个最小窗口字串

图解

分析

代码

class Solution {
    public String minWindow(String s, String t) {
        int[] freqT = new int[256];
        int[] freqS = new int[256];
        int count = t.length();
        String result = "";
        int start = 0;

        for(int i = 0; i< t.length();i++){
            freqT[t.charAt(i)]++;
        }

        for(int i = 0; i< s.length();i++){
            char c = s.charAt(i);
            if(freqT[c] >0){
                freqS[c]++;

                if(freqT[c]>=freqS[c]){
                    count--;
                }
            }

            if(count==0){
                while(freqS[s.charAt(start)] > freqT[s.charAt(start)] || freqT[s.charAt(start)] ==0){
                    if(freqS[s.charAt(start)] > freqT[s.charAt(start)]){
                        freqS[s.charAt(start)]--;
                    } 
                    start++;
                }
               if(result.equals("") || i- start +1 < result.length()){
                   result = s.substring(start, i+1);
               } 

            }
        }    
        return result; 
    }
}

results matching ""

    No results matching ""