The user inputs the strings s1 and s2. Find the smallest substring of the string s1 that contains all the letters of s2. (if there are more than one of equal size, find the first one that appears)
Example input:
it is raining today
dot
Output: tod
Note: I wrote a working code, but it took me too much time to figure out and write, and since I'll have such examples on a test, that isn't good. Is there a simpler way?
How I did it: I wrote two functions, one that returns a substring from index i to index j for a given string, and another to check whether the substring contains all letters. Then I used them to find the shortest substring that contains all the letters by using nested for loops.
My code (working):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
const int LEN = 100;
char *subString(int beg, int end, int n, char str[n])
{
int resultLen = abs(end - beg), i;
char *result = malloc(sizeof(char) * resultLen);
for (i = 0; i < resultLen; i++)
{
result[i] = str[i + beg - 1];
}
return result;
}
int doesSubstrContainAllLetters(int substrLen, int lettersLen, char substr[substrLen], char letters[lettersLen])
{
int i, j, result = 1;
char *containtChar;
for (i = 0; i < lettersLen; i++)
{
containtChar = strchr(substr, letters[i]);
if (containtChar == 0)
{
result = 0;
}
else
{
*containtChar = '+';
}
}
return result;
}
int main()
{
char s1[LEN], s2[LEN];
gets(s1);
gets(s2);
int s1Len = strlen(s1);
int s2Len = strlen(s2);
int res, min_substrLen = INT_MAX, substrLen, i, j, c;
for (i = 0; i < s1Len - 1; i++)
{
for (j = i + 1; j < s1Len; j++)
{
char *substr = subString(i, j, s1Len, s1);
substrLen = strlen(substr);
res = doesSubstrContainAllLetters(strlen(substr), s2Len, substr, s2);
if (res == 1)
{
min_substrLen = (substrLen < min_substrLen) ? substrLen : min_substrLen;
}
}
}
for (i = 0; i < s1Len - 1; i++)
{
for (j = i + 1; j < s1Len; j++)
{
char *substr = subString(i, j, s1Len, s1);
substrLen = strlen(substr);
res = doesSubstrContainAllLetters(strlen(substr), s2Len, substr, s2);
if (res == 1 && substrLen == min_substrLen)
{
char *substr = subString(i, j, s1Len, s1);
printf("%s", substr);
return 0;
}
}
}
return 0;
}