-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path076-Minimum Window Substring.c
47 lines (46 loc) · 1.15 KB
/
076-Minimum Window Substring.c
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
char* minWindow(char* s, char* t) {
int count[128], needmatch = 0, min = INT_MAX;
memset(count, 0, sizeof(int)*128);
while (*t != '\0') {
count[*t]--;
needmatch++;
t++;
}
if (needmatch == 0) return t;
char* minstart = s, *minend = s;
char* start = s, * end = s;
while (*end != '\0') {
if (needmatch == 0 && *end == *start) {
start++;
while (count[*start] > 0) {
count[*start]--;
start++;
}
} else {
if (count[*end] < 0) {
needmatch--;
}
count[*end]++;
}
if (needmatch == 0) {
while (count[*start] > 0) {
count[*start]--;
start++;
}
if (end-start+1 < min) {
minstart = start;
minend = end;
min = end - start + 1;
}
}
end++;
}
char* res = malloc(minend - minstart + 2);
if (min == INT_MAX) {
res[0] = '\0';
} else {
memcpy(res, minstart, min);
res[min] = '\0';
}
return res;
}