leetcode题解-76. Minimum Window Substring

来源:互联网 发布:海尔区域网络专员 编辑:程序博客网 时间:2024/06/10 19:00

题目: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的最小子串。其实于上一道题目很相像,不过本题是寻找包含t的最小子串,而上一题是寻找s中本身包含的所有不同字符的子串。
首先还是最简单的暴力法,直接两个循环,但是效率很低。代码入下,很简单不做过多解释。

    public static String minWindow(String s, String t) {        String ss = "";        int min = s.length();        Map<Character, Integer> map = new HashMap<>();        for(char c : t.toCharArray()) map.put(c, map.getOrDefault(c, 0)+1);        for(int i=0; i<s.length(); i++){            Map<Character, Integer> tmp = new HashMap<>();            for(int j=i; j<s.length(); j++){                char c = s.charAt(j);                if(map.containsKey(c)){                    if(tmp.containsKey(c) && tmp.get(c) < map.get(c))                        tmp.put(c, tmp.get(c)+1);                    else if(!tmp.containsKey(c))                        tmp.put(c, 1);                    if(tmp.equals(map) && min>j-i){                        min = j-i;                        ss = s.substring(i, j+1);                        break;                    }                }            }        }        return ss;    }

方法二,使用两个数组分别保存t的内容和遍历过的s的内容。然后使用两个游标进行遍历。具体的解释写在代码里。这种发发击败了88%的用户。

 public static String minWindow1(String s, String t){        char [] tt = new char[256];        char [] ss = new char[256];        int count = 0;        int min = s.length()+1;        int begin = 0, end = 0;        for(char c : t.toCharArray()) tt[c]++;        for(int i=0, left=0; i<s.length(); i++){            char c = s.charAt(i);            if(tt[c] == 0)                continue;            ss[c] ++;            if(ss[c] <= tt[c])//当s累积的个数没有达到t时,count++。                count ++;            if(count == t.length()){                //如果遍历过的字符已经完全包含了t,则将left游标尽可能向右移动                char cc = s.charAt(left);                //left移动的规则就是,left索引位置的字符cc不在t中,或者ss中的cc个数>tt中的cc个数                while(ss[cc] > tt[cc] || tt[cc] == 0){                    if(ss[cc] > tt[cc])                        ss[cc] --;                    left ++;                    cc = s.charAt(left);                }                //如果count==t.length(),则说明已经找到了一个满足条件的子串。如果该子串长度更小,则更新其相应下标信息。                if(min > i-left+1){                    begin = left;                    end = i;                    min = i-left+1;                }            }        }        if(count != t.length())            return "";        return s.substring(begin, end+1);    }

这里记录了三种解决本题的思路和代码,有兴趣的同学可以看一看。

0 0