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<Character,Integer>,存有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()<t.length()){
			return "";
		}
        HashMap<Character,Integer> ht=new HashMap<>();
        int sum=t.length();
        for(i=0;i<t.length();i++){
        	if(ht.containsKey(t.charAt(i))){
        		ht.put(t.charAt(i), ht.get(t.charAt(i))+1);
        		
        	}else{
        		ht.put(t.charAt(i), 1);
        	}
        }
        int tail=0,head=0;
        int restail=Integer.MAX_VALUE,reshead=0;
        for(i=0;i<s.length();i++){
        	if(ht.containsKey(s.charAt(i))){       	
        		ht.put(s.charAt(i), ht.get(s.charAt(i))-1);
        		if(ht.get(s.charAt(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)<restail-reshead){
            		restail=tail;
            		reshead=head;
            	}
        	}
        	tail++;
        	if(tail==s.length()){
        		break;
        	}
        	if(ht.containsKey(s.charAt(tail))){
        		ht.put(s.charAt(tail), ht.get(s.charAt(tail))-1);
        	}      	
        }
        return s.substring(reshead,restail+1);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值