博客参考https://www.cnblogs.com/grandyang/p/4340948.html
leetcode--Minimum Window Substring
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).
主要思路
- 我们最开始先扫描一遍T,把对应的字符及其出现的次数存到 HashMap 中。
- 然后开始遍历S,就把遍历到的字母对应的 HashMap 中的 value 减一,如果减1后仍大于等于0(这里可以避免cnt记录多余的重复字母),cnt 自增1。
- 如果 cnt 等于T串长度时,开始循环,纪录一个字串并更新最小字串值。然后将窗口的左边界右移,如果某个移除掉的字母是T串中不可缺少的字母,那么 cnt 自减1,表示此时T串并没有完全匹配。
【在此题目中滑动窗口的右边界先扩张,当扩张到包含t字符串中的所有字母时,左边界再收缩,以取得当前的最小窗口,当窗口无法再收缩时,再进行右边界扩张,如此循环,直到找到整体的最小窗口】
public String minWindow(String s, String t)
{
//滑动窗口问题
String res = "";
int[] letterCnt = new int[128];
int left = 0, cnt = 0, minLen = s.length() + 1;
for(int i = 0; i< t.length() ; i++)
++letterCnt[t.charAt(i)];
for (int i = 0; i < s.length(); ++i) {
if (--letterCnt[s.charAt(i)] >= 0) ++cnt;
while (cnt == t.length()) {
if (minLen > i - left + 1) {
minLen = i - left + 1;
res = s.substring(left, left+minLen);
}
if (++letterCnt[s.charAt(left)] > 0) --cnt;
++left;
}
}
return res;
}
滑动窗口主要用来解决:子串,子数组,子序列等问题