KMP算法

印度小哥讲解KMP算法视频链接:

https://www.bilibili.com/video/av3246487?from=search&seid=5216993177757720410

代码连接:
https://github.com/mission-peace/interview/blob/master/src/com/interview/string/SubstringSearch.java

        //next数组实现伪代码
        //next [j] = k,代表j之前的字符串中有最大长度为k 的相同前缀后缀。
    
       void getnext()//获取next数组
    {
        int i,n,k;
        n=strlen(ptr);
        memset(next,0,sizeof(next));
        k=0;
        for(i=1;i<n;i++)
        {
            while(k>0 && ptr[k]!=ptr[i])//在无子串的时候不会到这里
                k=next[k];//如果不匹配就回溯到next[k]
            if(ptr[k]==ptr[i]) k++;//匹配到之后就k++
            next[i+1]=k;//将匹配到的字符个数存入
    	//next表示的是匹配长度
        }
   }

KMP算法:

int KmpSearch(char* s, char* p)
{
	int i = 0;
	int j = 0;
	int sLen = strlen(s);
	int pLen = strlen(p);
	while (i < sLen && j < pLen)
	{
		//①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++    
		if (j == -1 || s[i] == p[j])
		{
			i++;
			j++;
		}
		else
		{
			//②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]    
			//next[j]即为j所对应的next值      
			j = next[j];
		}
	}
	if (j == pLen)
		return i - j;
	else
		return -1;
}
原文地址:https://www.cnblogs.com/yonglin1998/p/11780844.html