POJ1226——Substrings
题意,给定一堆字符串,找出最大的公共子串。
//Date: 2015.04.25 //Time: 0ms //Memory: 144k #include <cstdio> #include <cstring> using namespace std; const int MAX_LEN=105; int n,index,length; char str[100][MAX_LEN]; void rev(char source[]){ //strrev()在POJ上编译无法通过 char c; int i,j=strlen(source)-1; for(i=0;i<j;i++){ c=source[i]; source[i]=source[j]; source[j--]=c; } } int SubString(){ bool found; int SubLen,i,j; char sub_string[MAX_LEN],rev_sub_string[MAX_LEN]; for(SubLen=length;SubLen;SubLen--){ for(i=0;i<=length-SubLen;i++){ strncpy(sub_string,str[index]+i,SubLen); strncpy(rev_sub_string,str[index]+i,SubLen); sub_string[SubLen]=rev_sub_string[SubLen]='\0'; rev(rev_sub_string); found=true; for(j=0;j<n;j++){ if( (strstr(str[j],sub_string)==NULL) && (strstr(str[j],rev_sub_string)==NULL) ){ found=false; break; } } if(found) return SubLen; } } return 0; } int main(){ int t,i,temp; scanf("%d",&t); while(t--){ length=105; scanf("%d",&n); getchar(); for(i=0;i<n;i++){ gets(str[i]); temp=strlen(str[i]); if(length>temp){ length=temp; index=i; } } printf("%d\n",SubString()); } return 0; }
原文:http://blog.csdn.net/zhangmh93425/article/details/45274425