手搓kmp朴素版{代码}
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 const int N = 1e5 + 10, M = 1e4 + 10; 7 8 int m, n; 9 string p, t; 10 11 int next1[M];//前缀数组 12 13 int main() 14 { 15 cin >> m >> p >> n >> t; 16 17 p = ' ' + p; 18 t = ' ' + t; 19 20 for (int i = 2, j = 0; i <= m; ++ i) { 21 while (j && p[i] != p[j+1]) j = next1[j]; 22 if(p[i] == p[j+1]) ++ j; 23 next1[i] = j; 24 } 25 26 for(int i = 1, j = 0; i <= n; ++ i) { 27 while (j && t[i] != p[j+1]) j = next1[j]; 28 if(t[i] == p[j+1]) ++ j; 29 if(j == m) { 30 j = next1[j]; 31 cout << i - m << ""; 32 } 33 } 34 return 0; 35 }
追求吾之所爱