HDU-1238 Substrings stl的运用

本文介绍了一种算法,用于解决寻找一组字符串中公共子串的最长长度的问题。通过枚举最小字符串的所有子串,并检查这些子串是否存在于其他字符串中,最终确定最长的公共子串长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
题意:
求每组给定字符串的公共子串的最长大小。
解题思路:
数据量小,直接枚举最小字符串的每个子串,依次匹配,注意STL的运用。
代码:

#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
bool cmp(string x,string y){return x.size()>y.size();}
string::size_type idx,id;
int main(){
	int n;
	scanf("%d",&n);
	while(n--){
		int m,maxx=0,flag=1;
		scanf("%d",&m);
		vector<string>q;
		for(int i=0;i<m;++i){
			string s;
			cin>>s;
			q.push_back(s);
		}
		sort(q.begin(),q.end(),cmp);		//其实没必要,只是试一下自定义排序
		string s=q[0];
		int len=s.size();
		for(int i=0;i<len;++i)
			for(int l=len;l>0;--l){
				flag=1;
				for(int j=1;j<m;++j){
					string ss=s.substr(i,l);
					string sss=ss;
					reverse(sss.begin(),sss.end());			//字符串反转
					idx=q[j].find(ss);id=q[j].find(sss);		//查找字串
					if(idx==string::npos&&id==string::npos){	//没找到
						flag=0;
						break;
					}
				}
				if(flag&&l>maxx){
					maxx=l;
					flag=1;
				}
			}
		printf("%d\n",maxx);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值