76. Minimum Window Substring

来源:互联网 发布:网络水军如何找站 编辑:程序博客网 时间:2024/05/16 14:03

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.

一刷没ac
解题思路:滑动窗口,先向右滑动再向右收缩。

public class Solution {    public String minWindow(String s, String t) {        if(s == null || t == null || s.length() == 0 || t.length() == 0) return "";        int[] map = new int[256];        char[] sarr = s.toCharArray();        char[] tarr = t.toCharArray();        for(char c : tarr){            map[c]++;        }        int count = t.length();        int begin = 0, end = 0, d = Integer.MAX_VALUE, head = 0;        while(end < sarr.length){            if(map[sarr[end++]]-- > 0) count--;            while(count == 0){                if(d > end-begin){                    d = end-begin;                    head = begin;                }                if(map[sarr[begin++]]++ == 0) count++;            }        }        if(d == Integer.MAX_VALUE) return "";        return s.substring(head, head+d);    }}
0 0
原创粉丝点击