leetcode76题 Minimum Window Substring

最小窗口子字符串

题目要求:给定一个字符串S和T,在S中找到一个包含T中所有字符的最短字串,时间复杂度为O(n).
注1:如果这个窗口不存在,返回一个空字符串
注2:该题保证在S中总是只有一个唯一的最小窗口

解决思路

采用滑动窗口的方法,首先定义一个HashMap集合,用来记录T中字符出现的次数,同时定义一个计数变量来统计所得到的字符串是否包含T中所有的字符。
具体做法为:当定义的滑动窗口的右指针不断向右滑动,找到包含T中所有字符的字串。然后通过控制窗口的滑动,尽可能的减少该字串的长度。

Java语言解决方案

class Solution {
    public String minWindow(String s, String t) {
        if(s.length()return "";

        char[] ss = s.toCharArray();
        char[] tt = t.toCharArray();

        int count = t.length();
        String res = "";
        HashMap hm = new HashMap<>();

        for(int i=0;iif(hm.containsKey(tt[i]))
                hm.put(tt[i], hm.get(tt[i])+1);
            else
                hm.put(tt[i], 1);               

        int l=0,r=0;

        while(rif(hm.containsKey(ss[r])){
                if(hm.get(ss[r])>0)
                    count--;
                hm.put(ss[r], hm.get(ss[r])-1);
            }

         while(l<=r&&count==0){
                if(res.isEmpty()||res.length()>(r-l+1))
                    res = s.substring(l,r+1);

                if(hm.containsKey(ss[l])){
                    hm.put(ss[l], hm.get(ss[l])+1);
                    if(hm.get(ss[l])>0)
                        count++;
                }
                l++;                            
            }   


            r++;
        }

       return res;
    }
}

题目链接: https://leetcode.com/problems/minimum-window-substring/description/

你可能感兴趣的:(leetcode)