lintcode(32)最小子串覆盖

描述:

给定一个字符串source和一个目标字符串target,在字符串source找到包括所有目标字符串字母的子串。

样例:

给出source = "ADOBECODEBANC"target = "ABC" 满足要求的解  "BANC"

思路:

先确定是不是子串,然后缩小范围

public class Solution {
    /**
     * @param source: A string
     * @param target: A string
     * @return: A string denote the minimum window
     *          Return "" if there is no such a string
     */
    public String minWindow(String source, String target) {
        // write your code
        int s = source.length();
        int t = target.length();
        String result = "";
        HashMap<Character , Integer> tar = new HashMap<Character , Integer>();
        for(int i = 0;i<t;i++){
            char ta = target.charAt(i);
            if(tar.containsKey(ta)){
                tar.put(ta , tar.get(ta) + 1);
            }else{
                tar.put(ta , 1);
            }
        }
        
        HashMap<Character , Integer> record = new HashMap<Character , Integer>();
        int count = 0;
        int right = 0;
        boolean change = false;
        for(int i = 0;i<s;i++){
            char so = source.charAt(i);
            if(record.containsKey(so)){
                record.put(so , record.get(so) + 1);
                if(tar.containsKey(so) && tar.get(so) >= record.get(so)){
                    count++;
                }
            }else{
                record.put(so , 1);
                if(tar.containsKey(so) && tar.get(so) >= record.get(so)){
                    count++;
                }
            }
            if(count == t){
                right = i;
                change = true;
                break;
            }
        }
        if(change){
            result = source.substring(0 , right+1);
            int left = 0;
            char m = result.charAt(left);
            while(!tar.containsKey(m) || record.get(m) > tar.get(m)){
                if(tar.containsKey(m) && record.get(m) > tar.get(m)){
                    record.put(m , record.get(m) - 1);
                }
                left++;
                m = result.charAt(left);
            }
            result = result.substring(left);
        }
        return result;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值