【Leetcode刷題篇】leetcode76 最小覆蓋子串
阿新 • • 發佈:2020-12-27
給你一個字串 s 、一個字串 t 。返回 s 中涵蓋 t 所有字元的最小子串。如果 s 中不存在涵蓋 t 所有字元的子串,則返回空字串 “” 。
注意:如果 s 中存在這樣的子串,我們保證它是唯一的答案。
示例 1:
輸入:s = “ADOBECODEBANC”, t = “ABC”
輸出:“BANC”
示例 2:
輸入:s = “a”, t = “a”
輸出:“a”
class Solution {
public String minWindow(String s, String t) {
// 對輸入字串判斷
if(s==null || s=="" ||t==null||t==""||s.length()<t.length()) {
return "";
}
// 用來統計t中每個字元出現的次數
int[] needs = new int[128];
for(int i=0;i<t.length();i++) {
needs[t.charAt(i)]++;
}
// 用來統計滑動視窗中每個字元出現的次數
int[] window = new int[128];
int left = 0, right = 0;
String res = "";
int count = 0;
// 用來記錄最短需要多少個字元
int minLength = s.length()+1;
while(right<s.length()) {
char ch = s.charAt(right);
window[ch]++;
if(needs[ch]>0&&needs[ ch]>=window[ch]) {
count++;
}
// 移動到不滿足條件為止
while(count==t.length()) {
ch = s.charAt(left);
if(needs[ch]>0&&needs[ch]>=window[ch]) {
count--;
}
if(right-left+1<minLength) {
minLength = right-left+1;
res = s.substring(left,right+1);
}
// 滑動視窗 移動
window[ch]--;
left++;
}
right++;
}
return res;
}
}