leetCode练习(76)

题目:Minimum Window Substring

难度:hard

问题描述:

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.

解题思路:

求S的最小子串,使得子串包含T的所有字符,且每个字符的出现次数不小于T中的。

构造hashmap,存有T中所有字符出现的次数。遍历S,遇到T中字符,则表中该字符出现次数-1,知道找到子串S(0,i)包含T。然后0往后走,I也往后走。直到I=S.lenngth-1。找到其中满足的子串中最短的子串即可。

具体代码如下:

public static String minWindow(String s, String t) {
		int i;
		if(s.length() ht=new HashMap<>();
        int sum=t.length();
        for(i=0;i=0){    			
        			sum--;  
        			if(sum==0){
                		i++;
                		break;
                	}
        		}
        	}          	
        }        
        tail=i-1;   
        if(sum!=0){
        	return "";
        }
        restail=tail;
        reshead=head;            
        while(true){
        	while(true){
        		if(ht.containsKey(s.charAt(head))){    		
            		if(ht.get(s.charAt(head))<0){         		
                		ht.put(s.charAt(head), ht.get(s.charAt(head))+1);
                		head++;
                	}else{
                		break;
                	}
            	}else{
            		head++;
            	}           	
            	if((tail-head)

你可能感兴趣的:(leetCode)