# LeetCode 76. Minimum Window Substring - Java - 滑动窗口

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).

### Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"


### Note:

• If there is no such window in S that covers all characters in T, return the empty string "".
• If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

### Java代码

/**
* <p>创建日期：2020-05-23 9:00</p>
*
* @author PengHao
*/
class Solution {
public String minWindow(String s, String t) {
char[] sArr = s.toCharArray();

Map<Character, Integer> window = new HashMap<>(t.length() >> 1);
Map<Character, Integer> tMap = new HashMap<>(t.length() >> 1);
// 初始化Map
for (char ch : t.toCharArray()) {
tMap.put(ch, tMap.getOrDefault(ch, 0) + 1);
}

// 滑动窗口中满足条件且不重复的字符个数
int numOfValidUnrepeatedCharInWindow = 0;
// 窗口边界，[left, right)
int left = 0, right = 0;
// 最小覆盖子串的起始索引和长度
int minLeft = 0, minLen = s.length() + 1;
// 扩大窗口
while (right < s.length()) {
// 进入窗口的字符，并右移窗口右边界
char enterChar = sArr[right++];
// 判断字符串t中是否有该字符
if (tMap.containsKey(enterChar)) {
// 如果有该字符，更新数据
// 窗口中该字符个数加1
window.put(enterChar, window.getOrDefault(enterChar, 0) + 1);
// 判断窗口中该字符的个数是否等于满足条件
if (window.get(enterChar).equals(tMap.get(enterChar))) {
// 满足条件，个数加1
numOfValidUnrepeatedCharInWindow++;
}
}
// 判断窗口是否满足缩小的条件
while (numOfValidUnrepeatedCharInWindow == tMap.size()) {
// 判断当前窗口长度是否小于最小长度
if (minLen > right - left) {
minLen = right - left;
minLeft = left;
}
// 移出窗口的字符，并右移窗口左边界
char outChar = sArr[left++];
// 判断窗口中是否有该字符
if (window.containsKey(outChar)) {
// 判断该字符个数是否刚好满足条件
if (window.get(outChar).equals(tMap.get(outChar))) {
// 不满足条件，个数减1
numOfValidUnrepeatedCharInWindow--;
}
// 字符个数减1
window.put(outChar, window.get(outChar) - 1);
}
}
}
return minLeft + minLen > s.length() ? "" : s.substring(minLeft, minLeft + minLen);
}
}


### 参考

12-02 86

07-25 943

05-04 438

05-13 30

02-03 251

07-16 205

10-03 2013

08-22 45

03-17 221

11-17 3565

03-23 2642

05-22 439

01-21 1125

03-19 398

11-08 247

05-14 100

08-12 111

07-09 92

09-17 289

04-14 59万+

03-13 15万+

03-04 14万+

03-08 2万+

04-25 7万+

03-10 13万+

03-10 19万+

03-12 11万+

03-13 11万+

03-18 1万+

03-19 8万+

03-19 4万+

03-22 5万+

03-23 4万+

03-24 3万+

03-25 3万+

05-08 5万+

03-25 9万+

03-29 22万+

03-29 10万+

03-30 17万+

06-01 7056

06-01 1万+

04-02 1万+

04-02 6640

04-02 4万+

04-06 1万+

04-06 7万+

04-09 8万+

04-09 3万+

05-17 9561

04-11 4万+

04-15 6万+

04-18 5万+

04-20 5万+

04-24 3万+

05-01 6843

05-03 1万+

05-16 5万+

05-06 2万+

05-07 4202

05-07 1万+

05-08 4万+

05-10 3872

05-14 7281

05-16 4129

05-16 1万+

05-17 5581

05-30 2113

05-20 1328

05-18 2770

05-18 9147

05-27 1856

05-18 4205

05-28 1572

05-19 1万+

05-19 2215

05-21 8892

05-21 9058

#### 老码农吐血建议：2020年，低于1w的程序员要注意了...

©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客