Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11464 Accepted Submission(s): 5504Problem 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
orchidSample Output
2
2Author
Asia 2002, Tehran (Iran), Preliminary
题解
1、题意就是找出n个字符串中相同的子串的长度(逆子串也可以)。
2、思路:
- 找到n个字符串中最小长度字符串
- 将最小长度字符串不断循环减短与另外的字符串比较
- 主要理解以下几个函数
- strlen:求字符串长度
- strncpy:strncpy()原型: char * strncpy(char *dest, const char *src, size_t n);
- strstr:strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
-
-
代码
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
char s[101][101];
int m;
//反转
void rechange(char *str)
{
int len;
int j=0;
char rs[101];
len=strlen(str);
for(int i=0;i<len;i++)
{
rs[j++]=str[len-i-1];
}
rs[j]='\0';
strcpy(str,rs);
}
int GetStr(char *str)
{
char p[101];//模拟子串
char k[101];//模拟反转子串
int len1,len2;
int flag;
len1=strlen(str);
len2=strlen(str);
while(len1>0)
{
for(int i=0;i<=len2-len1;i++)
{
/******/
strncpy(p,str+i,len1);
strncpy(k,str+i,len1);
p[len1]='\0';
k[len1]='\0';
rechange(k);
flag=1;
for(int d=0;d<m;d++)
{
if(strstr(s[d],p)==NULL&&strstr(s[d],k)==NULL)
{
flag=0;
break;
}
}
if(flag==1)
{
return len1;
}
}
len1--;
}
}
int main()
{
int n;
char min_char[101];
cin>>n;
while(n--)
{
//int m;
int min_length=100;
cin>>m;
for(int i=0;i<m;i++)
{
cin>>s[i];
if(strlen(s[i])<min_length)
{
strcpy(min_char,s[i]);
min_length=strlen(min_char);
}
}
int sublen=GetStr(min_char);
cout<<sublen<<endl;
}
return 0;
}
本文介绍了一种算法,用于从多个字符串中寻找最长的相同子串(包括其逆序子串),并提供了一个完整的C++实现示例。该算法首先确定输入字符串中最短的一个作为基准,然后逐步缩短此字符串并与其它字符串进行比较。
929

被折叠的 条评论
为什么被折叠?



