LintCode:最小子串覆盖
2015-11-24 23:14
288 查看
给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出source = "ADOBECODEBANC",target = "ABC" 满足要求的解
"BANC"
注意
如果在source中没有这样的子串,返回"",如果有多个这样的子串,返回起始位置最小的子串。
挑战
要求时间复杂度为O(n)
说明
在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
标签 Expand
解题思路:
用sourcehash[ ]和targethash[ ]来保存字符串的每个字符的保存个数。
再加上利用双指针
您在真实的面试中是否遇到过这个题?
Yes
样例
给出source = "ADOBECODEBANC",target = "ABC" 满足要求的解
"BANC"
注意
如果在source中没有这样的子串,返回"",如果有多个这样的子串,返回起始位置最小的子串。
挑战
要求时间复杂度为O(n)
说明
在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。
标签 Expand
解题思路:
用sourcehash[ ]和targethash[ ]来保存字符串的每个字符的保存个数。
再加上利用双指针
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 if(source==null||source.length()==0) return ""; int targetHash[] = new int[256]; int sourceHash[] = new int[256]; /**初始化targetHash[]**/ for(int i=0;i<target.length();i++){ targetHash[target.charAt(i)]++; } int end = 0; int min = Integer.MAX_VALUE; String res = ""; for(int start =0;start<source.length();start++){ while(isValueble(targetHash, sourceHash)&&end<source.length()){ sourceHash[source.charAt(end)]++; end++; } if(!isValueble(targetHash, sourceHash)&&(end-start)<min){ min = end-start; res = source.substring(start,end); } sourceHash[source.charAt(start)]--; } return res; } public boolean isValueble(int targetHash[],int sourceHash[]){ for(int i = 0;i<targetHash.length;i++){ if(targetHash[i]>sourceHash[i]){ return true; } } return false; } }
相关文章推荐
- Linux网络poll模型
- [Android] 解析android framework下利用app_process来调用java写的命令及示例
- select * from table1 where id =‘1’ for update
- jdbc将数据库连接信息放置配置文件中
- A simple water problem
- LintCode:最大数
- Python yield与实现
- JVM内存区域
- ack工具
- spring MVC学习(一)---前端控制器
- leetcode Merge K sorted Lists python
- JDK自带方法实现RSA数字签名
- Shell学习笔记 - 运算符
- IOS UIDatePicker
- C++类中的枚举类型
- hdu2512 Bell数
- Python自学笔记
- php中curl的参数详解
- a
- LintCode:最大子数组差