Minimum Window Substring

来源:互联网 发布:nginx tcp代理 编辑:程序博客网 时间:2024/04/29 14:58

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.

分析:

同样是滑动窗口问题;

这里需要借助map,初始map中存放T中的字符以及字符个数,然后right指针开始向后遍历,直到窗口中含有了T中的所有字符,这里以一个变量count进行计数;当然只有在right指针指向的字符在T中而且该字符在map中对应的数量大于0时才能count+1,因为如果其对应的数量已经等于0了,说明窗口中已经包含了T中该字符的数量,当前这个是多余的;

当count等于T的长度时,计算窗口大小,并且与当前的最小窗口大小进行比价,同时记录窗口起始位置;left指针开始起作用,逐渐往前遍历直到含有T中字符,对map进行补全;直到不再含有T中的某一个字符为止;

发现map的使用真心巧妙!!!

参考代码:

http://blog.csdn.net/linhuanmars/article/details/20343903

public class Solution {    public String minWindow(String S, String T) {    if(S==null || S.length()==0)        return "";    HashMap<Character, Integer> map = new HashMap<Character, Integer>();    for(int i=0; i<T.length();i++)    {        if(map.containsKey(T.charAt(i)))        {            map.put(T.charAt(i),map.get(T.charAt(i))+1);        }        else        {            map.put(T.charAt(i),1);        }    }    int left = 0;    int count = 0;    int minLen = S.length()+1;    int minStart = 0;    for(int right=0; right<S.length();right++)    {        if(map.containsKey(S.charAt(right)))        {            map.put(S.charAt(right),map.get(S.charAt(right))-1);            if(map.get(S.charAt(right))>=0)            {                count++;            }            while(count == T.length())            {                if(right-left+1<minLen)                {                    minLen = right-left+1;                    minStart = left;                                    }                if(map.containsKey(S.charAt(left)))                {                    map.put(S.charAt(left), map.get(S.charAt(left))+1);                    if(map.get(S.charAt(left))>0)                    {                        count--;                    }                }                left++;            }        }    }    if(minLen>S.length())    {        return "";    }    return S.substring(minStart,minStart+minLen);}}


0 0
原创粉丝点击