Leetcode -- Minimum Window Substring

来源:互联网 发布:网站特效源码 编辑:程序博客网 时间:2024/05/01 12:31

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;    }


0 0