LeetCode 76. Minimum Window Substring(java)

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.

以下的代码解法是从直接看第i位的数,然后分情况讨论的原子操作想法出发,1. i不属于T,do nothing; 2. i属于T,2.1 已经存在结果,那么freq(s.charAt(i))++, move start until Tfreq(start) == Sfreq(start), 2.2 不存在结果,freq(s.charAt(i))++, 如果此时存在了,那么delete until Tfreq(start) == Sfreq(start).
public static String minWindow(String s, String t) {
        //T-Table
        int count = 0, start = 0, min = Integer.MAX_VALUE;
        String res = "";
        int[] mapT = new int[256];
        for (int i = 0; i < t.length(); i++) {
            mapT[t.charAt(i)]++;
        }
        //S-Table
        int[] mapS = new int[256];
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (mapT[c] > 0) {
                mapS[c]++;
                if (count >= t.length()) {
                    //move start
                    start = moveStart(start, mapS, mapT, s);
                } else {
                    if (mapT[c] >= mapS[c]) {
                        count++;
                        if (count >= t.length()) {
                            start = moveStart(start, mapS, mapT, s);
                        }
                    }
                }  
            }
            if (count >= t.length() && i - start + 1 < min) {
                    min = i - start + 1;
                    res = s.substring(start, i + 1);
            }
        }
        return res;
    }
    public static int moveStart(int start, int[] mapS, int[] mapT, String s) {
        while (mapT[s.charAt(start)] == 0 || mapS[s.charAt(start)] > mapT[s.charAt(start)]) {
            if (mapT[s.charAt(start)] > 0) {
                mapS[s.charAt(start)]--;                                            
            }
            start++;
        }
        return start;
    }
阅读更多
文章标签: java leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 76. Minimum Window Substring(java)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭