1 int* Getnext(char *p,int len_p){//p为模式串 2 int *Next = new int[len_p]; 3 Next[0] = -1; 4 int j = -1,i=0; 5 while(i < len_p){//自身与自身匹配 6 while(j != -1&&p[j]!=p[i])//移动匹配串 7 j = Next[j]; 8 j+=1; 9 Next[++i] = j; 10 } 11 return Next; 12 } 13 vector<int>* Kmp(char *s,char *p,int len_s,int len_p){//s为主串,p为匹配串 14 int *Next = Getnext(p,len_p);//求得Next数组 15 int j = 0;//j为匹配串匹配到的位置 16 vector<int>* ans = new vector<int>();//ans为匹配到的主串的开头下标位置 17 for(int i=0;i < len_s;i++){ 18 while(j != -1 && s[i] != p[j]) 19 j = Next[j]; 20 j+=1; 21 if(j == len_p){//匹配串匹配完毕 22 ans->push_back(i - len_p + 1); 23 j = Next[j];//j退回到Next[j] 24 } 25 } 26 return ans; 27 }
原文地址:https://www.cnblogs.com/xfww/p/8585148.html
时间: 2024-10-22 14:55:03