字符串算法模版.docVIP

  • 3
  • 0
  • 约3.4千字
  • 约 12页
  • 2017-03-09 发布于江苏
  • 举报
字符串算法模版

一些字符串算法模版 1、KMP算法(敖教主整理的模版) /*注意:以下函数的数组下标都是从0开始。*/ //函数功能:求KMP的next函数。next[]={-1,1,...}。O(n) //参数1:char A[],模式串A,下标从0开始。 //参数2:int n,模式串A的大小。 //参数3:int next[],next[j]=x定义为前j个字符的首位x个元素相同,所以next[n]=x表示...且next[0]=-1,所以next[]={-1,0,...} void KMP_GetNext(char B[],int n,int next[]) { next[0]=-1; int i=0,j=-1; while(in) { if(j==-1 || B[i]==B[j]) { i++; j++; next[i]=j; } else j=next[j]; } } //函数功能:KMP主函数,求第一次匹配的数组下标,不匹配返回-1。O(n) //参数1:char A[],主串。 //参数2:int len_a,主串长。 //参数3:char B[],模式串。 //参数4:int len_b,模式串长。 //参数5:int next[],next[j]=x,表示前j个字符的首位x个字符相同,即最大移动距离。 int KMP_GetIndex(char A[],int len_a,char B[],int len_b,int next[]) { int i=0,j=0; while(ilen_a jlen_b) { if(j==-1 || A[i]==B[j]) { i++; j++; } else j=next[j]; } if(j==len_b) return i-j; else return -1; } //函数功能:返回主串A中(允许重叠)子串B的个数。O(n) //参数1:char A[],主串。 //参数2:int len_a,主串长。 //参数3:char B[],模式串。 //参数4:int len_b,模式串长。 //参数5:int next[],next[j]=x,表示前j个字符的首位x个字符相同,即最大移动距离。 int KMP_GetMany(char A[],int len_a,char B[],int len_b,int next[]) { int i=0,j=0,sum=0; while(ilen_a jlen_b) { if(j==-1 || A[i]==B[j]) { i++; j++; } else j=next[j]; if(j==len_b) { sum++; j=next[j]; } } return sum; } //函数功能:返回主串A中(不重叠)子串B的个数。O(n) //参数1:char A[],主串。 //参数2:int len_a,主串长。 //参数3:char B[],模式串。 //参数4:int len_b,模式串长。 //参数5:int next[],next[j]=x,表示前j个字符的首位x个字符相同,即最大移动距离。 int KMP_GetManyDiv(char A[],int len_a,char B[],int len_b,int next[]) { int i=0,j=0,sum=0; while(ilen_a jlen_b) { if(j==-1 || A[i]==B[j]) { i++; j++; } else j=next[j]; if(j==len_b) { sum++; j=0; } } return sum; } 扩展KMP 扩展KMP其实就是求出字符串B的后缀与字符串A的最长公共前缀extend[i]表示B[i...B_len] 与A的最长公共前缀长度,也就是要计算这个数组对于extend[]数组来说,则可以利用它直接解决匹配问题,只要看extend[]数组元素是否有一个等于len_A即可这个数组保存了更多更丰富的信息,即B的每个位置与A的匹配长度。 void GetExtendNext(const char *mode, int *next, const int modlen) { int a, p, j = -1; next[0] = 0; for (int i = 1; i modlen; i++,j--) { if (j 0 || i + next[i - a] = p) { if (j 0) j = 0, p = i; while (p modlen mode[p] == mode[j]) ++p, ++j; next

文档评论(0)

1亿VIP精品文档

相关文档