312 - 最小子串覆盖

2017.9.18

题目本身应该不难

首先从源字符串的第一个字符开始查找,如果在target包含这个字符则在target中去掉这个字符。

查找完毕时,如果target为空串,则表示源字符串中是包含目标字符串的。期间需要记录start和end的位置。


第一次查找完毕时,需要从start+1的位置重新进行查找,如果找到的新的字符串的长度小于上边查找到的字符串的长度,则进行结果的替换工作。


中间遇到的问题是,如果字符串中包含 "*","?","+"等正则表达式的时候,使用string.replace就会出现问题,就需要特殊处理一下。加上双斜杠。

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 static String minWindow(String source , String target) {
        // write your code here
    	String res = "";
        if(source.equals("") || source.length() < target.length()){
        	return res;
        }
        String tmp = target;
        int start = 0;
        int end = 0;
        for(int i = 0; i < source.length();i++){
        String ss = Character.toString(source.charAt(i));
        	if(tmp.contains(ss)){
        		if(tmp.equals(target)){
        			start = i;
        		}
        		if(ss.equals("*") || ss.equals("?") || ss.equals("+")){
        			ss = "\\" + ss;
        		}
        		tmp = tmp.replaceFirst(ss, "");
        		if(tmp.equals("")){
        			end = i;
        			break;
        		}
        	}
        }
        if(!tmp.equals("")){
        	return res;
        }
        else{
        	res = source.substring(start, end+1);
        }
        if(res.length() == target.length()){
        	return res;
        }
        String res_tmp = minWindow(source.substring(start+1) , target);
        if(!res_tmp.equals("") && res_tmp.length() < res.length()){
        	res = res_tmp;
        }
        return res;
    }

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值