题目:http://poj.org/problem?id=3080
Sample Input
3 2 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 3 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA 3 CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
Sample Output
no significant commonalities AGATAC CATCATCAT
题目要求:每组数据给你n个串,找出这n个串的最长的公共子串(子串必须是连续的)。如果存在多个最长的公共子串,输出字典序最小的
那个。如果公共子串的长度<3的话,就输出指定那句话。
1.strncpy(ans, s[0]+i, j-i+1 ); //挖串的函数,类似于C++的s.strsub(),无返回值
参数:(被赋值串,提取串的起始地址, 提取的长度)
2.strcmp(s, t); 比较两个串的大小,有返回值
3.strstr(s, t); 查找t串在s串中的位置,如果不存在则返回NULL,否则返回第一个出现下标,有返回值
4.strcpy(s, t); 赋值函数,无返回值
代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <iostream> #include <string> #include <algorithm> using namespace std; char p[11][61];//最多有10个串 每个串最长60 int main() { int tg; scanf("%d", &tg); int i, j, k; int n; while(tg--) { scanf("%d%*c", &n); for(i=0; i<n; i++) scanf("%s", p[i]); int len; char ans[61]=" "; len=0; //枚举p[0]的每个子串 int len0=strlen(p[0]); for(i=0; i<len0; i++){//枚举子串的起始位置 for(j=i+2; j<len0; j++){//枚举子串的结束位置 char cur[61]; strncpy(cur, p[0]+i, j-i+1);//将该子串挖出来 cur[j-i+1]=' '; //最后一个位置赋值成' '才可以当字符串处理 bool flag=true; for(k=1; k<n; k++) { if(strstr(p[k], cur)==NULL ){ flag=false; break;// } } if( flag==true && ( (j-i+1)>len || (j-i+1)==len &&strcmp(ans, cur)>0) ) { len=j-i+1; strcpy(ans, cur); } } } if(len<3) printf("no significant commonalities "); else printf("%s ", ans ); } return 0; }