Hard
Sliding window的典型題,LC Discuss里面給了模版討論,需要再練幾道找找感覺.
總體的sliding window思路
- Use two pointers: start and end to represent a window.
- Move end to find a valid window.
- When a valid window is found, move start to find a smaller window.
本題要先用一個hashMap來記錄t里面每個character出現的頻數. 初始化two pointers start, end == 0. count表示還需要在s里找到count個t中含有的character, 初始化為t.length(). minStart表示最后找到的minimum window substring的start index, minLen表示該min window substring的長度,初始化為s.length() + 1.
然后我們移動end去找一個valid的window.首先看s.charAt(end)是不是在t里,這個時候我們檢查hash里面有沒有這個key并且要保證該key對應的value是大于0的.(可能遇到雖然t里有char a, 但是已經被找到了的情況,這個時候就不能繼續像沒找到時第一次找到那樣操作). 如果有,那么我們就在找到了一個t里邊有的char, 所以還需要找的char數目count就減1.
這句話蠻重要:hash.put(ch, hash.getOrDefault(ch, 0) - 1);
如果t里面有這個char,那現在找到了就得把它在t里的頻數減1;如果t里面沒有,說明hash以前也沒有這個key, 我們就加一個這個key, 并且在它的默認value 0的基礎上減一到-1.
為什么要這么寫呢?因為后面while (count == 0)
里面要用到. 就是當我們要移動start去找一個更小的valid windows時,會去檢查s.charAt(start)是不是在t里,從而決定要不要對count增一。這時候我們先將頻數還原:hash.put(cha, hash.getOrDefault(cha, 0) + 1);
.這里如果原來的t里有該char,那得到的get(char)就肯定會大于0,如果原來沒有,那么之前我們刪頻數的時候肯定得到get(char) == -1,所以現在的value會是0. 所以下一步我們只需要判斷hash.get(char) > 0? 就可以決定要不要對count增一了。簡單來講就是我移動窗口左端點的時候,檢查看看左端點那個char是不是t里面的,如果是我就得讓需要在s里找到的在t里存在的char數目增加一,不是就不需要。
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> hash = new HashMap<>();
for (char c : t.toCharArray()){
hash.put(c, hash.getOrDefault(c, 0) + 1);
}
//s = "ab"
//t = "b"
//hash:("a"->0, "b"->0)
int start = 0, end = 0;
int count = t.length();
int minStart = 0, minLen = s.length() + 1;
while (end < s.length()){
char ch = s.charAt(end);
if (hash.containsKey(ch) && hash.get(ch) > 0){
count--;
}
hash.put(ch, hash.getOrDefault(ch, 0) - 1);
while (count == 0){
if (end - start + 1< minLen){
minLen = end - start + 1;
minStart = start;
}
char cha = s.charAt(start);
hash.put(cha, hash.getOrDefault(cha, 0) + 1);
if (hash.containsKey(cha) && hash.get(cha) > 0){
count++;
}
start++;
}
end++;
}
if (minLen == s.length() + 1){
return "";
} else {
return s.substring(minStart, minStart + minLen);
}
}
}
對于hash的處理也可以一開始就把s的每一個char都當作hash的key,但value為0;只有在t里面存在的才統計頻數。這樣可能不那么confusing!
class Solution {
public String minWindow(String s, String t) {
Map<Character, Integer> hash = new HashMap<>();
for (char c : s.toCharArray()){
hash.put(c, 0);
}
for (char c : t.toCharArray()){
hash.put(c, hash.getOrDefault(c, 0) + 1);
}
//s = "ab"
//t = "b"
//hash:("a"->0, "b"->0)
int start = 0, end = 0;
int count = t.length();
int minStart = 0, minLen = s.length() + 1;
while (end < s.length()){
char ch = s.charAt(end);
if (hash.get(ch) > 0){
count--;
}
hash.put(ch, hash.get(ch) - 1);
while (count == 0){
if (end - start + 1< minLen){
minLen = end - start + 1;
minStart = start;
}
char cha = s.charAt(start);
hash.put(cha, hash.get(cha) + 1);
if (hash.get(cha) > 0){
count++;
}
start++;
}
end++;
}
if (minLen == s.length() + 1){
return "";
} else {
return s.substring(minStart, minStart + minLen);
}
}
}