76-最小窗口子串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LaputaFallen/article/details/79949775

Description:

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.


问题描述
给定字符串S和T,在O(n)的时间复杂度下找出S中包含T所有字符的最小窗口。
例如,S = “ADOBECODEBANC”, T = “ABC”, 返回”BANC”


问题分析
注意题目要求是包含所有字符就可以了,不需要注意顺序
这种题下面这个链接总结的模板非常好,建议看一下:
https://leetcode.com/problems/minimum-window-substring/discuss/26808/Here-is-a-10-line-template-that-can-solve-most-‘substring’-problems


解法

class Solution {
    public String minWindow(String s, String t) {
        int[] map = new int[128];

        for(char c : t.toCharArray())  map[c]++;

        int counter = t.length(), start = 0, end = 0, d = Integer.MAX_VALUE, minstart = 0;

        while(end < s.length()){
            char c = s.charAt(end);
            if(map[c] > 0)  counter--;
            map[c]--;
            end++;
            while(counter == 0){
                if(end - start < d){
                    d = end - start;
                    minstart = start;
                }
                char c1 = s.charAt(start);
                if(map[c1] == 0)    counter++;
                map[c1]++;
                start++;
            }
        }

        return d == Integer.MAX_VALUE ? "" : s.substring(minstart, minstart + d);
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

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