题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2594
简单的KMP算法应用~~~
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 using namespace std; 4 5 const int N = 50002; 6 char str1[N]; 7 char str2[N]; 8 int next[N]; 9 10 void get_next(int len_1); 11 int kmp_search(int len_1, int len_2); 12 13 int main() 14 { 15 int len; 16 while(scanf("%s%s", str1, str2) != EOF) 17 { 18 int len_1 = strlen(str1); 19 int len_2 = strlen(str2); 20 get_next(len_1); 21 len = kmp_search(len_1, len_2); 22 if(len == 0) 23 { 24 printf("0\n"); 25 } 26 else 27 { 28 for(int i = 0; i < len; i++) 29 { 30 printf("%c", str1[i]); 31 } 32 printf(" %d\n", len); 33 } 34 } 35 return 0; 36 } 37 38 void get_next(int len_1) 39 { 40 int i = 0; 41 int j = -1; 42 next[i] = -1; 43 while(i < len_1) 44 { 45 if(j == -1 || str1[j] == str1[i]) 46 { 47 i++; 48 j++; 49 if(str1[i] == str1[j]) 50 { 51 next[i] = next[j]; 52 } 53 else 54 { 55 next[i] = j; 56 } 57 } 58 else 59 { 60 j = next[j]; 61 } 62 } 63 } 64 65 int kmp_search(int len_1, int len_2) 66 { 67 int i = 0; 68 int j = 0; 69 while(i < len_2) 70 { 71 if(j == -1 || str1[j] == str2[i]) 72 { 73 i++; 74 j++; 75 } 76 else 77 { 78 j = next[j]; 79 } 80 } 81 if(j == -1) 82 { 83 return 0; 84 } 85 if(j == 0) 86 { 87 if(str1[0] == str2[len_2 - 1]) 88 { 89 return 1; 90 } 91 else 92 { 93 return 0; 94 } 95 } 96 else 97 { 98 return j; 99 } 100 }