LeetCode_76_MinimumWindowSubstring
題目分析:
和上題一個意思屯蹦,找序列滿足某種條件的串逻卖。只是又回到字符串了。雙指針。
解法:
public static String minWindow(String s, String t) {
String result = "";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < t.length(); i++)
map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) + 1);
int count = map.size();
int left = 0, right = 0, minLength = s.length() + 1;
for (; right < s.length(); right++) {
//湊到某字符一個
if(map.containsKey(s.charAt(right))){
int tempNum = map.get(s.charAt(right));
map.put(s.charAt(right), tempNum - 1);
//剛好湊到某個字符 0 == tempNum - 1 而不是 0 >= tempNum - 1 因為count代表還有多少"種"字符要湊
if(0 == tempNum - 1)
count--;
//湊到所有字符所需所有
while(0 == count){
//若是更短的值 取出來
if(right - left + 1 < minLength) {
minLength = right - left + 1;
result = s.substring(left, left + minLength);
}
//如果接下來左移要排除的是t中的字符,要更新count
if(map.containsKey(s.charAt(left))){
int tempLeft = map.get(s.charAt(left));
map.put(s.charAt(left), tempLeft + 1);
if(tempLeft + 1 > 0) ++count;
}
//上面已經(jīng)保存了當前的最小值,可以left++直接假定至少丟一個開頭再繼續(xù)奕坟,后面找不出補位的結束就是正確結果
left++;
}
}
}
return result;
}