hdoj 1238 SubStrings (子字符串问题)

思路:先找到所有字符串里最短的那个,并且枚举它所有的子串(包括正负),然后用这些子串和别的字符串比较(有现成的strstr函数)因为数据量不大,不用担心超时问题;

代码如下:

#include <iostream>  
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>

using namespace std;
void clear(char (*a)[110])//初始化
{
	int i, j;
	for (i = 0; i < 110; i++)
		for (j = 0; j < 110; j++)
			a[i][j] = '\0';
}

int main()
{
	int t;
	int n;
	int i,x,y;
	char a[110][110];
	char base[110];
	int len[110],lenmin,lenpoint;
	int head, tail;//子串的头尾
	int flag,key;
	
	char temp1[110],temp2[110];
	cin >> t;
	while (t--)
	{
		cin >> n;
		getchar();
		clear(a);
		flag = 0;//代表找到后,或者找完了,直接退出循环
		key = 1;//代表有没有找到 
		for (i = 0; i < n; i++)
		{
			scanf("%s", a[i]);
			len[i] = strlen(a[i]);
		}
		lenmin = len[0];
		lenpoint = 0;
		for (i = 0; i < n; i++)
		{
			if (len[i] < lenmin)
			{
				lenmin = len[i];
				lenpoint = i;
			}
		}
		strcpy(base, a[lenpoint]);
		for (i = lenmin; i >= 1; i--)//枚举最短字符串的所有子串(从最长子串开始)
		{
			if (flag)
				break;
			
			
			for (head = 0, tail = head + i; tail <= lenmin; head++,tail++)
			{
				y = 0;
				key = 1;//初始化
				flag = 0;
				memset(temp1, 0, sizeof(temp1));//对子串初始化
				memset(temp2, 0, sizeof(temp2));
				for (x = head; x < tail; x++)//得到子串(正)
				{
					temp1[y++] = base[x];
				}
				y = 0;
				for (x = tail - 1; x >= head; x--)
					temp2[y++] = base[x];
				temp1[y] = temp2[y] = '\0';
				for (x = 0; x < n; x++)
				{
					
					if (strstr(a[x], temp1) == NULL && strstr(a[x], temp2) == NULL) 
					{
						key = 0;
						
						break;
					}
						
				}
				if (key)
				{
					flag = 1;
					cout << strlen(temp1) << endl;
					break;
				}
			}

		}
		if (!key)
		{
			cout << "0" << endl;

		}
	}
	system("pause");
	return 0;
}
	


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值