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.
该题与LeetCode 438. Find All Anagrams in a String很相似,都是根据一个串,来寻求另一个串中满足某种规则的所有子串。所以该题也同样用滑动窗口 + map[] 来做。 不同之处在于,该题寻求的子串是变长的,而438寻求的子串是固定长度的。固定长度便要求,一旦到达了长度,那么窗口左指针必须右移。而该题是只要 diff 为0,便将缩小窗口。
经验教训
两题的对比
滑动窗口 + map 来处理子串或子数组问题。
代码实现
class Solution {
public String minWindow(String s, String t) {
if (s == null || t == null) {
return"";
}
int sLen = s.length();
int tLen = t.length();
if (tLen > sLen) {
return"";
}
int[] map = newint[256];
for (int i = 0; i < tLen; i++) {
++map[t.charAt(i)];
}
int diff = tLen;
int left = 0;
int right = 0;
//minLeft,minRight 用来标志找到的最短子串的前后索引int minLeft = 0;
int minRight = sLen;
while (right < sLen) {
//窗口加right位置的数,发生了哪些改变if (map[s.charAt(right)] > 0) {
--diff;
}
--map[s.charAt(right)];
while (diff == 0 ) {
//更新minLeft,与minRightif (right - left + 1 < minRight - minLeft + 1) {
minLeft = left;
minRight = right;
}
//左侧缩小窗口,直至diff不为0,说明又该扩大窗口了if (map[s.charAt(left)] >= 0) {
++diff;
}
++map[s.charAt(left)];
++left;
}
//扩大窗口
right++;
}
return minRight == sLen ? "" : s.substring(minLeft, minRight + 1);
}
}
题目描述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 “BA...