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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值