lintcode--32. 最小子串覆盖
2018-02-27 21:22
375 查看
描述
给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。注意事项
如果在source中没有这样的子串,返回”“,如果有多个这样的子串,返回起始位置最小的子串。说明
在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
样例
给出source = "ADOBECODEBANC",target = "ABC" 满足要求的解 "BANC"
代码
import java.util.*; 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 here if("".equals(source)||"".equals(target)){ return ""; } int[] map=new int[256]; for(int i=0;i<target.length();i++){ map[target.charAt(i)]++; } int start=0,end=source.length()-1,j=0,min=Integer.MAX_VALUE,minS=-1,minE=source.length()-1; int[] freq=new int[256]; int i; for(i=0,start=i;i<source.length();i++){ freq[source.charAt(i)]++; //计算每一个字符出现的频数 if(freq[source.charAt(i)]<=map[source.charAt(i)]){ //判断该字符是否在target中出现过 j++; } if(j==target.length()){ //找到了一个子串 //为了让start指向第一个符合要求的字符。 while(start<i&&(freq[source.charAt(start)]>map[source.charAt(start)])){ freq[source.charAt(start)]--;//还原无效的字符的频数 start++; } if(i-start<min){ min=i-start; end=i; minS=start; } //继续寻找下一个子串,start加1,复原freq在start位置的频数,j减1。 freq[source.charAt(start++)]--; j--; } } if(minS==-1){ return ""; } return source.substring(minS,end+1); } }
相关文章推荐
- lintcode最小子串覆盖
- lintcode--最小子串覆盖
- lintcode 中等题:minimum window substring 最小子串覆盖
- LintCode:M-最小子串覆盖
- lintcode(32)最小子串覆盖
- 32. 最小子串覆盖
- lintcode-32-最小子串覆盖
- LintCode-直方图最大矩形覆盖
- lintcode:直方图最大矩形覆盖
- LintCode 32 最小子串覆盖
- lintcode-最小子串覆盖-32
- LintCode : 验证二叉查找树
- lintcode 摆动排序(Wiggle Sort) (Java)
- LintCode Python 54.转换字符串到整数
- Codevs 3027 线段覆盖 2 序列dp
- LintCode Update Bits
- LintCode 407-加一
- lintcode -- 线段树的构造
- Lint Code——最多共线的点的个数
- LintCode "Longest Increasing Subsequence"