kmp
Posted kangdong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了kmp相关的知识,希望对你有一定的参考价值。
1 #include<iostream> 2 #include<string> 3 #include<cstring> 4 using namespace std; 5 6 void kmp_pre(char x[], int m, int Next[]) 7 { 8 int i, j; 9 j = Next[0] = -1; 10 i = 0; 11 while (i < m) 12 { 13 int mark1=j,mark2=j; 14 while (-1 != j && x[i] != x[j]) mark1=j,j = Next[j],mark2 = j; 15 Next[++i] = ++j; 16 cout << "(" << i <<","<< mark1<<" " <<mark2 << " " << j << ")"; 17 } 18 cout << endl; 19 } 20 int Next[10010]; 21 int KMP_Count(char x[], int m, char y[], int n) 22 { 23 int i, j; 24 int ans = 0; 25 kmp_pre(x, m, Next); 26 for (int i = 0; i < m+1; i++) 27 cout << Next[i]<<" "; 28 cout << endl; 29 i = j = 0; 30 while (i < n) 31 { 32 while (-1 != j && y[i] != x[j]) j = Next[j]; 33 i++; j++; 34 if (j >= m) 35 { 36 ans++; 37 j = Next[j]; 38 } 39 } 40 return ans; 41 } 42 int main() 43 { 44 char a[100], b[100]; 45 cin >> a >> b; 46 int lena = strlen(a), lenb = strlen(b); 47 cout << KMP_Count(a, lena, b, lenb) << endl; 48 return 0; 49 }
以上是关于kmp的主要内容,如果未能解决你的问题,请参考以下文章