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.
题目链接:https://leetcode.com/problems/minimum-window-substring/
题目分析:典型的尺取法问题,先标记下T串有哪些字符及它们的个数,固定左端点,移动右端点直到包含整个T串,然后移动左端点直到不再包含整个T串,此时再继续移动右端点,击败了91%
public class Solution {
public String minWindow(String s, String t) {
int lens = s.length();
int lent = t.length();
int[] cnt = new int[300];
boolean[] mark = new boolean[300];
for (int i = 0; i < lent; i ++) {
cnt[t.charAt(i)] ++;
mark[t.charAt(i)] = true;
}
int sz = lens + 5, l = 0, num = 0, lpos = 0;
for (int r = 0; r < lens; r ++) {
char cur = s.charAt(r);
if (mark[cur]) {
cnt[cur] --;
if (cnt[cur] >= 0) {
num ++;
}
}
while (num == lent) {
if (r - l + 1 < sz) {
sz = r - l + 1;
lpos = l;
}
if (mark[s.charAt(l)]) {
cnt[s.charAt(l)] ++;
if (cnt[s.charAt(l)] > 0) {
num --;
}
}
l ++;
}
}
if (sz <= lens) {
return s.substring(lpos, lpos + sz);
}
return "";
}
}

本文详细解析了一道经典的字符串处理问题——寻找包含特定字符集的最小子串。通过使用尺取法,有效地解决了复杂度为O(n)的问题。文章提供了完整的Java实现代码,并对其运行流程进行了详细的解释。
424

被折叠的 条评论
为什么被折叠?



