字符串匹配算法-kmp

int Compare(string P, int *prefix) { int m = P.length(); prefix[0] = -1; int k = -1; for(int i = 1; i < m; i++) { while(k >= 0 && P[k + 1] != P[i]) k = prefix[k]; if(P[k + 1] == P[i]) k = k + 1; prefix[i] = k; } } //判读P是否是T的子串 void Kmp(string T, string P) { int n = T.length(); int m = P.length(); int prefix[m]; Compare(P, prefix); int k = -1; for(int i = 0; i < n; i++) { while(k >= 0 && P[k + 1] != T[i]) k = prefix[k]; if(P[k + 1] == T[i]) k = k + 1; if(k == m - 1) { cout << " I found " << i - m + 1 << endl; k = prefix[k]; } } }

下面是判读T和P是否是循环数,如“strstr”和"trstrs"就是循环数。

int Compare(string P, int *prefix) { int m = P.length(); prefix[0] = -1; int k = -1; for(int i = 1; i < m; i++) { while(k >= 0 && P[k + 1] != P[i]) k = prefix[k]; if(P[k + 1] == P[i]) k = k + 1; prefix[i] = k; } } //判读T和P是否是循环数,如“strstr”和"trstrs"就是循环数。 bool Kmp(string T, string P) { int n = T.length(); int m = P.length(); if(n != m) return false; int prefix[m]; Compare(P, prefix); int k = -1; for(int i = 0; i < 2*n - 1; i++) { while(k >= 0 && P[k + 1] != T[i % n]) k = prefix[k]; if(P[k + 1] == T[i % n]) k = k + 1; if(k == m - 1) { //cout << " I found " << i - m + 1 << endl; return true; //k = prefix[k]; } if(i == n -1 && -1 == k) break; } return false; }

变量和函数的名字都欠缺考虑,希望不要见怪!

 

你可能感兴趣的:(算法,C++,算法,string)