Given a set T of characters and a string S, find the minimum window in S which will contain all the characters in T in complexity O(n).
eg,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_OUT_LEN 256
int min_window(char *str, char *dest, int &min_begin, int &min_end)
{
char need_to_find[256] = {0};
char has_found[256] = {0};
int begin = 0, end = 0;
int count = 0;
int str_len = 0, dest_len = 0;
int i = 0;
int min_window_len = MAX_OUT_LEN;
if(str == NULL || dest == NULL)
{
printf("input wrong!\n");
return -1;
}
str_len = strlen(str);
dest_len = strlen(dest);
for(i = 0; i < dest_len; i++)
{
need_to_find[dest[i]]++;
}
for(begin = 0, end = 0; end < str_len; end++)
{
if(need_to_find[str[end]] == 0)
{
continue;
}
has_found[str[end]]++;
if(has_found[str[end]] <= need_to_find[str[end]])
{
count++;
}
if(count == dest_len)
{
int get_len = 0;
while(need_to_find[str[begin]] == 0 || has_found[str[begin]] > need_to_find[str[begin]])
{
if(has_found[str[begin]] > need_to_find[str[begin]])
{
has_found[str[begin]]--;
}
begin++;
}
get_len = end - begin + 1;
if(get_len < min_window_len)
{
min_begin = begin;
min_end = end;
min_window_len = get_len;
}
}
}
return count == dest_len ? 0 : -1;
}