一、问题描述
描述
给出两个字符串 s 和 t,要求在 s 中找出最短的包含 t 中所有字符的连续子串。
数据范围:0 \le |S|,|T| \le100000≤∣S∣,∣T∣≤10000,保证s和t字符串中仅包含大小写英文字母
要求:进阶:空间复杂度 O(n)O(n) , 时间复杂度 O(n)O(n)
例如:
S ="XDOYEZODEYXNZ"S="XDOYEZODEYXNZ"
T ="XYZ"T="XYZ"
找出的最短子串为"YXNZ""YXNZ".
注意:
如果 s 中没有包含 t 中所有字符的子串,返回空字符串 “”;
满足条件的子串可能有很多,但是题目保证满足条件的最短的子串唯一。
示例1
输入:
"XDOYEZODEYXNZ","XYZ"
返回值:
"YXNZ"
示例2
输入:
"abcAbA","AA"
返回值:
"AbA"
二、解题思路
1.问题分析
区间计数
2.解题代码
import java.util.*;
public class Solution {
/**
*
* @param S string字符串
* @param T string字符串
* @return string字符串
*/
public boolean check(int[] count){
for(int i=0;i<256;++i){
if(count[i]> 0 )
return false;
}
return true;
}
public String minWindow (String S, String T) {
// write code here
int[] count = new int[256];
for(int i=0;i<256;++i){
count[i] = 0;
}
for (int i=0; i<T.length(); ++i) {
count[(int)T.charAt(i)] += 1;
}
int start=0, end = Integer.MAX_VALUE;
for (int i=0,j=0; j<S.length(); ){
count[(int)S.charAt(j)] -= 1;
if(check(count)){
// System.out.println("ok");
while(check(count)) {
// System.out.println("ok2");
if (j + 1 - i < end - start) {
end = j + 1;
start = i;
}
count[(int)S.charAt(i++)] += 1;
}
}
j++;
}
//System.out.println("start="+start+",end="+end);
if(end==Integer.MAX_VALUE){
end = 0;
}
return S.substring(start, end);
}
}