首页 > 代码库 > Substrings(hdu1238)字符串匹配
Substrings(hdu1238)字符串匹配
Substrings
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7205 Accepted Submission(s): 3255
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
这个找字串的问题,题目大概意思就是找出所有字符串中共同拥有的一个子串,
该子串(正、逆字符)是任何一个母串的子串,求该子串的最长长度。
想到用STRING里的成员函数和STL的reverse反转函数,
思路:
先找出最短的母串,即该符合要求的子串肯定在这个母串中,即在从长到短
从最短母串中取子串,在子串正反去查看是否符合要求。
说实话今天又学到了一些知识,我表示这C++的很多函数真shi 强大啊。
ps:http://acm.hdu.edu.cn/showproblem.php?pid=1238
#include<iostream>#include<string>#include<algorithm>//STL reverse函数的头文件,reverse反转函数,using namespace std;int main(){ int cas,len,sub,maxn; int n,k,i,j; string s[102]; cin>>cas; while(cas--) { cin>>n; len=1000; sub=0; for(i=0; i<n; i++) { cin>>s[i]; if(len>s[i].size())//找最小 的母串 { len=s[i].size(); sub=i; } } maxn=0; for(i=s[sub].size(); i>0; i--) //从最小的母串开始从长到短找子串, { for(j=0; j<s[sub].size()-i+1; j++) //长度为i的子串在母串中找 { string s1,s2;//s1为子串正 ,s2为子串反 s1=s[sub].substr(j,i);//去j开始i长度是字符 s2=s1; reverse(s2.begin(),s2.end());//反串 for( k=0; k<n; k++) { if(s[k].find(s1,0)==-1&&s[k].find(s2,0)==-1) //当正反子串在母串中都未发现时即跳出 break; } if(k==n&&maxn<s1.size()) maxn=s1.size(); } } cout<<maxn<<endl; } return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。