最小覆盖子串
给一个字符串S、一个字符串T,在字符串S里面找出:包含T的所有字符的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
My answer(不具有参考价值)
//滑动窗口+暴力,很明显会超时
class Solution {
public String minWindow(String s, String t) {
HashMap<Character, Integer> hash = new HashMap<>();
int start = 0;
int len_s = s.length();
int len_t = t.length();
int end = start+len_t;
int resStart = 0;
int resEnd = 0;
int minLength = 0;
while(start <= end && end < len_s){
char ch = s.charAt(end);
if(!hash.containsKey(ch)){
hash.put(ch,end);
}
boolean flag = true;
for(int i = 0; i < len_t;i++){
if(hash.containsKey(s.charAt(i)))
continue;
else{
flag = false;
}
}
if(flag){
if(minLength > end-start+1){
minLength = end-start+1;
resStart = start;
resEnd = end;
start++;
end++;
hash.clear();
}
}
else{
end++;
}
}
return s.substring(resStart,resEnd+1);
}
}
超时
优秀代码
class Solution {
public String minWindow(String s, String t) {
if(s==null||t==null||s.length()<t.length())
return "";
int min = Integer.MAX_VALUE;
int[] need = new int[128];
int left=0;
int right =0;
int start,end;
int cnt =0;
end=start=-1;
for(int i=0;i<t.length();i++)
need[t.charAt(i)]++;
while (right<s.length()){
if((--need[s.charAt(right)])>=0)
cnt++;
right++;
while (cnt==t.length()){
if(right-left<min){
min = right-left;
start=left;
end = right;
}
if((++need[s.charAt(left)])<=0){
left++;
continue;
}else {
left++;
cnt--;
}
}
}
if(start==-1)
return "";
return s.substring(start,end);
}
}
执行用时击败79.8%的用户
内存消耗击败20%的用户