一串首尾相连的珠子(m 个),有N 种颜色(N<=10), 设计一个算法,取出其中一段,要求包含所有N 中颜色,并使长度最短。并分析时间复杂度与空间复杂度。
#include <stdio.h>
#include <string.h>
#define N 256
int allin(char *b, int *c)
{
for(unsigned int i=0; i < strlen(b); i++)
{
if(c[b[i]] == 0)
return 0;
}
return 1;
}
void find_shortest(char *a, char *b, int *c)
{
int begin=0,end=0;
int len = strlen(a);
int short_len = len;
int short_begin;
while(begin < len)
{
while(!allin(b,c))
{
c[a[end%len]]++;
if(end == len && begin == 0)
{
printf("字符串不包含所有情况!\n");
return;
}
end++;
}
while(allin(b,c))
{
c[a[begin]]--;
begin++;
}
if(short_len > end - begin + 1)
{
short_len = end - begin + 1;
short_begin = begin - 1;
}
}
printf("最短子串长度为:%d\n",short_len);
printf("最短子串为:\n");
if(short_begin + short_len > len)
{
int i;
for(i=short_begin;i<len;i++)
printf("%c",a[i]);
for(i=0;i<short_len-(len-short_begin);i++)
printf("%c",a[i]);
}
else
{
int i;
for(i=short_begin;i<short_begin+short_len;i++)
printf("%c",a[i]);
}
printf("\n");
}
int main()
{
char a[] = "AABBCCDDBCDD";
char b[] = "ABCD";
printf("原字符串为:%s\n",a);
printf("需要匹配的字符数集为:%s\n",b);
int c[N] = {0};
find_shortest(a,b,c);
return 0;
}