题目描述
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.
思路分析
这题同样是使用滑动窗口的思想,根据快慢指针来找到最小的字符串。去之前有区别的地方就是T中的字符串和S中的子串并不是按序对应,只要满足T中的字符在S中的某一子串中都存在即可。所以我们先用Map把T中的字符存下来,key对应字符,value对应个数。然后去S中找,出现相同个数字符的子串。
实践证明用map比较麻烦、改用数组、因为题目提示是字符,一般的字符或者符号都可以用ASCii码表示,ASCII 码使用指定的7 位或8 位二进制数组合来表示128 或256 种可能的字符。java中char类型可以自动转化为int,只要不超出可以表示的范围。设一个大小为256的数组,下标为字符的值,对应的值是字符的个数。
代码
public String minWindow(String s, String t) {
if(s == null || t == null || s.length() < t.length()){
return "";
}
int[] temp=new int[256];
for (char c : t.toCharArray()) {
temp[c]++;
}
int count = t.length(),minLen = Integer.MAX_VALUE,start=0,end=0,head=0;
while(end<s.length())
{
if(temp[s.charAt(end++)]-->0)
{
count--;
}
//count=0,即S中存在子串覆盖了T中所有字符
while(count==0)
{
if(end-start<minLen)
{
minLen = end-start;
head = start;
}
//start向右移,使得其无法覆盖T中所有字符,寻找下一个可能项
if(temp[s.charAt(start++)]++ == 0)
{
count++;
}
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(head, head+minLen);
}