[搜狗] 找一个字符串中包含全部出现字符的最小字符串

一个字符串中含有n个字符,其中有m个不同的字符,n>>m,用最少的时间和空间找到包含所有这m个字符的最短的字串,不考虑特殊字符,只考虑字母数字即可。

例如:

abccbaddac,返回:cbad

aabcadbbbcca,返回:bcad

实现代码:

#include <iostream>
using namespace std;
void Search(char input[], char output[]);
int main()
{
	char* input = "abccbaddac";
	char* output = new char[strlen(input)];
	Search(input,output);
	cout<<output<<endl;
}

void Search(char input[], char output[])
{
	bool num[10] = {0}; //数字字符
	bool small[26] = {0}; //小写字符
	bool big[26] = {0}; //大写字符
	int sum = 0; //不同字符的个数
	int temp, index;
	for (int i = 0; i < strlen(input); i++)
	{
		temp = input[i];
		if (temp >= 97)
		{
			index = input[i] - 'a';
			if (small[index] == 0)
			{
				small[index] = 1;
				sum++;
			}
		}
		else if (temp <= 57)
		{
			index = input[i] - '0';
			if (num[index] == 0)
			{
				num[index] = 1;
				sum++;
			}
		}
		else
		{
			index = input[i] - 'A';
			if (big[index] == 0)
			{
				big[index] = 1;
				sum++;
			}
		}
	}

	bool t_num[10] = {0}; //数字字符
	bool t_small[26] = {0}; //小写字符
	bool t_big[26] = {0}; //大写字符
	int t_sum = 0;

	int min = strlen(input);
	char* out = new char[strlen(output) + 1];
	memset(out,0,sizeof(out));

	for (int i = 0; i < strlen(input); i++)
	{
		char* pout = out;
		t_sum = 0;
		memset(t_num,0,sizeof(t_num));
		memset(t_small,0,sizeof(t_small));
		memset(t_big,0,sizeof(t_big));
		int j = i;
		while(j < strlen(input))
		{
			*pout++ = input[j];
			temp = input[j];
			if (temp >= 97)
			{
				index = input[j] - 'a';
				if (t_small[index] == 0)
				{
					t_small[index] = 1;
					t_sum++;
				}
			}
			else if (temp <= 57)
			{
				index = input[j] - '0';
				if (t_num[index] == 0)
				{
					t_num[index] = 1;
					t_sum++;
				}
			}
			else
			{
				index = input[j] - 'A';
				if (t_big[index] == 0)
				{
					t_big[index] = 1;
					t_sum++;
				}
			}
			if (t_sum == sum)
			{
				int len = j - i;
				if(min > len)
				{
					min = len;
					*pout = '\0';
					strcpy(output,out);
					j = i + len - sum;
					break;
				}
			}
			j++;
		}
	}
	delete [] out;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值