题目:Minimum Window Substring
难度:hard
问题描述:
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC"
.
Note:
If there is no such window in S that covers all characters in T, return the empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
解题思路:
求S的最小子串,使得子串包含T的所有字符,且每个字符的出现次数不小于T中的。
构造hashmap<Character,Integer>,存有T中所有字符出现的次数。遍历S,遇到T中字符,则表中该字符出现次数-1,知道找到子串S(0,i)包含T。然后0往后走,I也往后走。直到I=S.lenngth-1。找到其中满足的子串中最短的子串即可。
具体代码如下:
public static String minWindow(String s, String t) {
int i;
if(s.length()<t.length()){
return "";
}
HashMap<Character,Integer> ht=new HashMap<>();
int sum=t.length();
for(i=0;i<t.length();i++){
if(ht.containsKey(t.charAt(i))){
ht.put(t.charAt(i), ht.get(t.charAt(i))+1);
}else{
ht.put(t.charAt(i), 1);
}
}
int tail=0,head=0;
int restail=Integer.MAX_VALUE,reshead=0;
for(i=0;i<s.length();i++){
if(ht.containsKey(s.charAt(i))){
ht.put(s.charAt(i), ht.get(s.charAt(i))-1);
if(ht.get(s.charAt(i))>=0){
sum--;
if(sum==0){
i++;
break;
}
}
}
}
tail=i-1;
if(sum!=0){
return "";
}
restail=tail;
reshead=head;
while(true){
while(true){
if(ht.containsKey(s.charAt(head))){
if(ht.get(s.charAt(head))<0){
ht.put(s.charAt(head), ht.get(s.charAt(head))+1);
head++;
}else{
break;
}
}else{
head++;
}
if((tail-head)<restail-reshead){
restail=tail;
reshead=head;
}
}
tail++;
if(tail==s.length()){
break;
}
if(ht.containsKey(s.charAt(tail))){
ht.put(s.charAt(tail), ht.get(s.charAt(tail))-1);
}
}
return s.substring(reshead,restail+1);
}