advancing4

题目描述[原题连接][https://leetcode-cn.com/problems/minimum-window-substring/]

给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字母的最小子串。

示例:

输入: S = “ADOBECODEBANC”, T = “ABC”
输出: “BANC”

说明:

如果 S 中不存这样的子串,则返回空字符串 “”。
如果 S 中存在这样的子串,我们保证它是唯一的答案。

算法描述

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string minWindow(string s, string t) {
int count[256] = {0};
for(auto c:t)++count[c];
int len = 0,minLength = s.length();
string res;
for(int l=0,r=0;r<s.length();++r){
count[s[r]]--;
if(count[s[r]]>=0)++len;
while(len == t.length()){
if(r-l+1<=minLength){
minLength = r-l+1;
res = s.substr(l,r-l+1);
}
count[s[l]]++;
if(count[s[l]]>0)--len;
++l;
}
}
return res;
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import javafx.util.Pair;

class Solution {
public String minWindow(String s, String t) {

if (s.length() == 0 || t.length() == 0) {
return "";
}

Map<Character, Integer> dictT = new HashMap<Character, Integer>();

for (int i = 0; i < t.length(); i++) {
int count = dictT.getOrDefault(t.charAt(i), 0);
dictT.put(t.charAt(i), count + 1);
}

int required = dictT.size();

List<Pair<Integer, Character>> filteredS = new ArrayList<Pair<Integer, Character>>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (dictT.containsKey(c)) {
filteredS.add(new Pair<Integer, Character>(i, c));
}
}

int l = 0, r = 0, formed = 0;
Map<Character, Integer> windowCounts = new HashMap<Character, Integer>();
int[] ans = {-1, 0, 0};

while (r < filteredS.size()) {
char c = filteredS.get(r).getValue();
int count = windowCounts.getOrDefault(c, 0);
windowCounts.put(c, count + 1);

if (dictT.containsKey(c) &&
windowCounts.get(c).intValue() == dictT.get(c).intValue()) {
formed++;
}

while (l <= r && formed == required) {
c = filteredS.get(l).getValue();

int end = filteredS.get(r).getKey();
int start = filteredS.get(l).getKey();
if (ans[0] == -1 || end - start + 1 < ans[0]) {
ans[0] = end - start + 1;
ans[1] = start;
ans[2] = end;
}

windowCounts.put(c, windowCounts.get(c) - 1);
if (dictT.containsKey(c) &&
windowCounts.get(c).intValue() < dictT.get(c).intValue()) {
formed--;
}
l++;
}
r++;
}
return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
}
}