解题思路:
法一:首先想到的是直接连接两个串,然后计算Next[],如果Next[Len] > 任意一个串的长度的化,回溯直到小于等于两个串的长度
1 #include <iostream> 2 #include <cstring> 3 #include <string> 4 #include <algorithm> 5 #include <cstdio> 6 #include <vector> 7 #define MAXSIZE 1000100 8 using namespace std; 9 10 string a; 11 int Next[MAXSIZE]; 12 int Len; 13 14 int GetNext() 15 { 16 int i = 0, j = Next[0] = -1; 17 while (i < Len) 18 { 19 if (j == -1 || a[i] == a[j]) 20 Next[++i] = ++j; 21 else 22 j = Next[j]; 23 } 24 } 25 26 int main(void) 27 { 28 ios::sync_with_stdio(false); 29 string t1, t2; 30 while (cin >> t1) 31 { 32 cin >> t2; 33 a = t1 + t2; 34 Len = a.size(); 35 GetNext(); 36 if (Next[Len] == 0) 37 cout << 0 << endl; 38 else if (Next[Len] <= t1.size() && Next[Len] <= t2.size()) 39 cout << a.substr(0, Next[Len]) << ' '<< Next[Len] << endl; 40 else 41 { 42 int p = Next[Len]; 43 //backtracking, until find smaller than t1 and t2 44 while (p > t1.size() || p > t2.size()) 45 p = Next[p]; 46 cout << a.substr(0, p) << ' ' << p << endl; 47 } 48 } 49 50 return 0; 51 }
法二:把第二个串当做母串,第一个串当做模式串,注:要比较到第二个串的尾部,当模式串(第一个串)全部比对成功后,如果没到尾部,扔要比对,直到尾部
#include <iostream> #include <cstring> #include <string> #include <algorithm> #define N 50010 using namespace std; char a[N]; char b[N]; int Next[N]; int Len_a, Len_b; void GetNext() { int i = 0, j = Next[0] = -1; while (i < Len_a) { if (j == -1 || a[i] == a[j]) Next[++i] = ++j; else j = Next[j]; } } int KMP() { int i = 0, j = 0; GetNext(); while (i < Len_b) { if (j == -1 || b[i] == a[j]) { i++; j++; } else j = Next[j]; } return j; } int main(void) { ios::sync_with_stdio(false); while (cin >> a >> b) { Len_a = strlen(a); Len_b = strlen(b); int res = KMP(); if (res) { for (int i = 0; i < res; ++i) cout << a[i]; cout << ' '; } cout << res << endl; } return 0; }