NEXT求取
查找主串中是否有子串,使用c语言实现:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void get_next(char* TS, char* next, int len);
void scan_position(char* TS, char* c, char* next);
int main()
{
char c[]="abcabcmn"; //查找的子串
char T[]="abcabeabcabcmn"; //主串
int len=strlen(c);
char *next=(char *) malloc(len);
if(next == NULL)
printf("request Error\r\n");//申请空间失败
get_next(c, next, len); //获取next值
scan_position(T, c, next); //查找主串中是否有子串
int i=0; //打印next值
while(i<len)
printf("%d ", next[i++]);
free(next);
return 0;
}
void get_next(char* TS, char* next, int len)
{
int i=0,j=0;
len--;next[0]=-1;
while(j<len)
{
if(j==0||TS[i]!=TS[j])
{
if(i) i=0;
else next[++j]=0;
}
else{ next[++j]=++i; }
}
}
void scan_position(char* TS, char* c, char* next)
{
int i=0,j=0;
int len=strlen(TS);
int clen=strlen(c);
char *str=NULL;
str=(char*)malloc(clen);
while(i<len&&j<clen)
{
if(TS[i]==c[j])
{
i++,j++;
}else{
if(j==0)i++;
else j = next[j];
}
}
if(j!=clen) printf("'%s'中没有找到'%s'\r\n", TS, c);
else{
memcpy(str, TS+i-j, j);
printf("T:%d %s\r\n", i-j, str);
}
free(str);
}
个人理解:
KMP算法,找到与头部相同的字符串,把每个位的相同数记录下来(next),这样能够为遍历时节约一部分回溯时间。