kmp算法水过,又重新熟悉了一下str的几个函数
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <cstdlib> 5 #include <cmath> 6 #include <map> 7 #include <algorithm> 8 #include <list> 9 #include <ctime> 10 #include <set> 11 #include <cstring> 12 #include <queue> 13 #include <cstdio> 14 #include <stack> 15 using namespace std; 16 const int wmax = 15; 17 const int wlen = 65; 18 char words[wmax][wlen]; 19 int words_len[wmax]; 20 int words_next[wmax][wlen]; 21 int wordNum; 22 #define CLR(arr, what) memset(arr, what, sizeof(arr)) 23 bool kmp(char A[], char B[], int P[], int n, int m) { 24 int j = -1; //表示已经匹配的位置 25 for (int i = 0; i < n; i++) { 26 while ((j > -1) && (B[j + 1] != A[i])) 27 j = P[j]; 28 if (B[j + 1] == A[i]) 29 j = j + 1; 30 if (j == m - 1) { 31 return true; 32 //cout << "Pattern occurs with shift: " << i - m + 1 << endl; 33 j = P[j]; 34 } 35 } 36 return false; 37 } 38 39 void next(int P[], char B[], int m) { 40 P[0] = -1; 41 int j = -1; 42 for (int i = 1; i < m; i++) { 43 while ((j > -1) && (B[j + 1] != B[i])) { 44 j = P[j]; 45 } 46 if (B[j + 1] == B[i]) 47 j = j + 1; 48 P[i] = j; 49 } 50 } 51 char wMax[wlen]; 52 char tmp[wlen]; 53 bool check(int lentmp){ 54 bool valid=true; 55 for (int i = 0; i < wordNum; i++) { 56 valid=valid&&(kmp(words[i],tmp,words_next[i],words_len[i],lentmp)); 57 if(!valid) 58 return false; 59 } 60 return true; 61 } 62 int main() { 63 int count; 64 bool judge; 65 cin >> count; 66 while (count--) { 67 cin >> wordNum; 68 int len_min=100; 69 int len_min_pos; 70 for (int i = 0; i < wordNum; i++) { 71 scanf("%s", words[i]); 72 words_len[i] = strlen(words[i]); 73 next(words_next[i],words[i],words_len[i]); 74 if(words_len[i]<len_min){ 75 len_min=words_len[i]; 76 len_min_pos=i; 77 } 78 } 79 int exists=0; 80 CLR(wMax,0); 81 for(int i=3;i<=len_min;i++){ 82 int fst=0; 83 CLR(tmp,0); 84 for(int j=0;j<len_min-i+1;j++){ 85 strncpy(tmp,words[len_min_pos]+j,i); 86 judge=check(i); 87 if(judge&&(0==fst)){ 88 strncpy(wMax,tmp,i); 89 fst=1; 90 exists=1; 91 }else if(judge&&(1==fst)){ 92 if(-1==(strcmp(tmp,wMax))){ 93 strncpy(wMax,tmp,i); 94 } 95 } 96 } 97 } 98 if(exists==1){ 99 cout<<wMax<<endl; 100 }else{ 101 cout<<"no significant commonalities"<<endl; 102 } 103 } 104 return 0; 105 }