您的位置:首页 > 其它

lintcode(32)最小子串覆盖

2017-04-22 10:06 351 查看
描述:

给定一个字符串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
4000
(!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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: