hdu 1238 & POJ 1226 Substrings

 

hdu题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1238

POJ题目链接:http://poj.org/problem?id=1226

Problem Description

You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.

 

 

Input

The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.

 

 

Output

There should be one line per test case containing the length of the largest string found.

 

 

Sample Input

2

3

ABCD

BCDFF

BRCD

2

rose

orchid

 

 

Sample Output

2

2

*******************************************************************************************************************

 

 题意:求最长公共子串。

 

方法:先找出最短的字符串,在此字符串上下手,从最长开始逐渐递减,直到找到为止。

 

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define FOR(i,n) for(i=0;i<n;i++)

using namespace std;
int n;
char str[110][110];//存放全部字符串 
char st[110];//寻找最短字符串short 
char revs[110];//字串的倒置strrev 
char vs[110];//去比较吧, 

void strev(){//HDU和POJ都不能识别strrev所还得自己写. 
//如果可以的话,直接strrev(str)。 
	char sw[110];
	int i,tot=0;
	strcpy(sw,revs);
	for(i=strlen(sw)-1;i>=0;i--)
		revs[tot++]=sw[i];
	revs[tot]='\0';
}

int Find(){
	int lens=strlen(st),rlens=strlen(st),i,j;
	bool flag;
	while(lens){//从最长的开始找 
		for(i=0;i<=rlens-lens;i++){
			strncpy(vs,st+i,lens);
			strncpy(revs,st+i,lens);//第二个复制,用于下面的倒置 
			vs[lens]=revs[lens]='\0';//尾问处理 
			strev();//没有参数,但每次调用的作用都是倒置revs 
			flag=true;
			for(j=0;j<n;j++){//比较全部字符串 
				if(!strstr(str[j],revs)&&!strstr(str[j],vs)){//如果两个都没有、做下面 
					flag=false;
					break;
				}
			}
			if(flag) return lens;
		}
		lens--;
	}
	return lens;//可能一个也没有,返回0 
}
//主函数 
int main(){
	int t,i,x=110;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		x=110;
		FOR(i,n){
			scanf("%s",str[i]);
			if(strlen(str[i])<x){//寻找最短的字符串 
				x=strlen(str[i]);
				strcpy(st,str[i]);
			}
		}
		printf("%d\n",Find());
	}
	return 0;
}


 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值