Leetcode -- Minimum Window Substring

本文介绍了一种在复杂度为O(n)的情况下,通过使用HashMap维护字符串S和T的字符匹配关系,找到S中包含T所有字符的最短子串的方法。

https://oj.leetcode.com/problems/minimum-window-substring/

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 emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.


public String minWindow(String S, String T)


很多跟window和string相关的题目都是用用HashMap来进行维护的,这一题也不例外。我们需要两个HashMap,第一个HashMap放T的内容作为匹配。两个指针,一头一尾,尾指针不停往第二个HashMap里面放内容,当我们判断到第二个HashMap的内容可以包含第一个的时候,头指针往尾指针靠,同时不停往第二个HashMap里面删除路过的内容,直到那种包含关系被打破。然后在这个过程里收集最短的window。

给出代码如下:

    public String minWindow(String S, String T) {
        HashMap<Character, Integer> char_map = new HashMap<Character, Integer>();
        for(char c : T.toCharArray())
            char_map.put(c, char_map.containsKey(c) ? char_map.get(c) + 1 : 1);
        int cur_size = 0;//实际上这就是用来判断是否处于包含关系的。
        String res = null;
        int head = 0;//头指针
        HashMap<Character, Integer> cached_map = new HashMap<Character, Integer>();
        for(int i = 0; i < S.length(); i++){
            Character cur_char = S.charAt(i);
            if(char_map.containsKey(cur_char)){
                cached_map.put(cur_char, cached_map.containsKey(cur_char) ? cached_map.get(cur_char) + 1 : 1);
                cur_size = cur_size + (cached_map.get(cur_char) <= char_map.get(cur_char) ? 1 : 0);
                if(cur_size == T.length()){
                    res = res == null ? S.substring(head, i + 1) : (i + 1 - head < res.length() ? S.substring(head, i + 1) : res);
                    while(cur_size == T.length()){//当一旦cached_map的内容包含了char_map了,就要找到第一个可以打破这个关系的位置即可。
                        Character remove_candidate = S.charAt(head);
                        if(cached_map.containsKey(remove_candidate)){
                            cached_map.put(remove_candidate, cached_map.get(remove_candidate) - 1);
                            if(cached_map.get(remove_candidate) < char_map.get(remove_candidate)){
                                res = i + 1 - head < res.length() ? S.substring(head, i + 1) : res;
                                cur_size--;
                            }
                        }
                        head++;
                    }
                }
            }
        }
        return res == null ? "" : res;
    }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值