1 題意:
尋找最長公共子串。
2分析:
<string.h>頭文件下:
a.strncpy()
b.strstr()
c.strcpy()
3
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn=16;
char str[maxn][100];
char sub_str[100];
char long_res[100];
int main()
{
int kk;
scanf("%d",&kk);
while(kk--){
int n;
scanf("%d",&n);
//memset(str,0,sizeof(str));
for(int i=1;i<=n;i++){
scanf("%s",str[i]);
}
int len=0;
for(int i=0;i<strlen(str[1]);i++){
for(int j=i+2;j<strlen(str[1]);j++){
///wrong: sub_str=strncpy(sub_str,str[1]+i,j-i+1);
strncpy(sub_str,str[1]+i,j-i+1);
sub_str[j-i+1]='\0';
int flag=true;
for(int k=2;k<=n;k++){
if(strstr(str[k],sub_str)==NULL){
flag=0;
break;
}
}
if(flag==1){
if( (len<(j-i+1)) || (len==j-i+1&&strcmp(sub_str,long_res)<0) ){
strcpy(long_res,sub_str);
len=j-i+1;
}
}
}
}
if(len<3)
cout<<"no significant commonalities"<<endl;
else
printf("%s\n",long_res);
}
return 0;
}