Skip to content

Commit 660ed9e

Browse files
Add 76 in c language
1 parent 341ddaa commit 660ed9e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

c/76-Minimum-Window-Substring.c

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every
3+
character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
4+
Space: O(1)
5+
Time: O(n+m) where n is the length of s and m the length of t
6+
*/
7+
8+
char * minWindow(char * s, char * t){
9+
int alpha[59] = {0};
10+
int need = 0;
11+
for (int i=0; t[i]!='\0'; i++) { // Initialise the alphabet
12+
if (alpha[t[i]-'A']==0)
13+
need++;
14+
alpha[t[i]-'A']--;
15+
}
16+
int maxLen = 100001;
17+
int pos=0;
18+
int i=0, j=0;
19+
while (s[j]!='\0') {
20+
alpha[s[j]-'A']++;
21+
if (alpha[s[j]-'A']==0) {
22+
need--;
23+
if (need==0) {
24+
while (alpha[s[i]-'A']>0) {
25+
alpha[s[i]-'A']--;
26+
i++;
27+
}
28+
if ((j-i+1)<maxLen) {
29+
pos = i;
30+
maxLen = j-i+1;
31+
}
32+
alpha[s[i]-'A']--;
33+
need++;
34+
i++;
35+
}
36+
}
37+
j++;
38+
}
39+
40+
if (maxLen==100001) { // No substring found
41+
char* ans = malloc(sizeof(char));
42+
ans[0] = '\0';
43+
return ans;
44+
} else {
45+
char* ans = malloc(sizeof(char)*(maxLen+1));
46+
for (int i=0; i<maxLen; i++)
47+
ans[i] = s[i+pos];
48+
ans[maxLen] = '\0';
49+
return ans;
50+
}
51+
}

0 commit comments

Comments
 (0)