标签:匹配 print turn size ext 出现 scan string can
? KMP算法每当一趟匹配过程中出现字符比较不等时,主串S中的i指针不需回溯,而是利用已经得到的“部分匹配”结果将模式向右“滑动”尽可能远的一段距离后,继续进行比较。
? KMP算法的主要核心其实就是next数组的求解
void GetNext(char *w, int next[])
{
//w为模式串
memset(next, 0, sizeof(next));
int i, j, len;
i = 0;
j = -1;
next[0] = -1;
len = strlen(w);
while(i < len)
{
if(j == -1 || w[i] == w[j])
{
i++;
j++;
if(w[i] != w[j])
next[i] = j;
else
next[i] = next[j];
}
else j = next[j];
}
}
int kmp(char *s, char *p, int next[])
{
int s_len = strlen(s);
int p_len = strlen(p);
int i = 0;
int j = 0;
int cnt = 0;
while(i < s_len && j < P_len)
{
if(j == -1 || s[i] == p[j])
{
i++;
j++;
}
else j = next[j];
}
if(j == p_len) return i-j;
else return -1;
}
#include<stdio.h>
#include<string.h>
int next[1000005];
char w[1000005];
char t[1000005];
void GetNext(char *w, int next[])
{
memset(next, 0, sizeof(next));
int i, j, len;
i = 0;
j = -1;
next[0] = -1;
len = strlen(w);
while(i < len)
{
if(j == -1 || w[i] == w[j])
{
i++;
j++;
if(w[i] != w[j])
next[i] = j;
else
next[i] = next[j];
}
else j = next[j];
}
}
int kmp(char *s, char *p, int next[])
{
int s_len = strlen(s);
int p_len = strlen(p);
int i = 0;
int j = 0;
while(i < s_len && j < p_len)
{
if(j == -1 || s[i] == p[j])
{
i++;
j++;
}
else j = next[j];
}
if(j == p_len) return i - j;
else return -1;
}
int main()
{
scanf("%s", w);
scanf("%s", t);
GetNext(w, next);
if(kmp(t, w, next) != -1) printf("匹配成功\n");
else printf("匹配失败\n");
return 0;
}
标签:匹配 print turn size ext 出现 scan string can
原文地址:https://www.cnblogs.com/Mrs-Jiangmengxia/p/13056419.html