Java for LeetCode 076 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.

解题思路:

涉及到查找操作,将T放进tMap中,同时创建一个保存T中所有字符(不重复)的图sMap,用一个计数器表示sMap和tMap的重合程度,一旦sMap包含了tMap即找到了一组解,通过收缩begin指针获取刚好包含tMap的位置,之后就是比较大小了,JAVA实现如下:

 public String minWindow(String s, String t) {
        HashMap<Character, Integer> tMap = new HashMap<Character, Integer>();
        HashMap<Character, Integer> sMap = new HashMap<Character, Integer>();
        for (int i=0;i<t.length();i++){
        	sMap.put(t.charAt(i), 0);  
            if (!tMap.containsKey(t.charAt(i)))
                tMap.put(t.charAt(i), 1);
            else
                tMap.put(t.charAt(i), tMap.get(t.charAt(i)) + 1); 
        }
        int begin=0,count=0,minBegin=0,length=s.length()+1;;
        for(int i=0;i<s.length();i++){
        	if(!tMap.containsKey(s.charAt(i)))
        		continue;
        	sMap.put(s.charAt(i), sMap.get(s.charAt(i))+1);
        	if(sMap.get(s.charAt(i))<=tMap.get(s.charAt(i)))
        		count++;
        	if(count==t.length()){
        		for(int j=begin;j<=i;j++){
        			if(!tMap.containsKey(s.charAt(j)))
        				continue;
        			if(sMap.get(s.charAt(j))>tMap.get(s.charAt(j))){
        				sMap.put(s.charAt(j),sMap.get(s.charAt(j))-1);
        				continue;
        				}
        			sMap.put(s.charAt(j),sMap.get(s.charAt(j))-1);
        			count--;
        			begin=j+1;
        			if(length>i-j){
        				length=i-j;
        				minBegin=j;
        			}
        			break;
        		}
        	}
        }
        return length!=s.length()+1?s.substring(minBegin, minBegin+length+1):"";
    }

 

posted @ 2015-05-18 20:56  TonyLuis  阅读(193)  评论(0编辑  收藏  举报