312

来源:互联网 发布:淘宝怎么解除限制登录 编辑:程序博客网 时间:2024/05/17 20:03

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;    }}


原创粉丝点击