hihocoder(1015) KMP

本文深入讲解了KMP算法的核心——Next数组(模式串的最长前缀后缀表),并提供了Next数组的计算方法及利用Next数组实现的KMP算法代码。通过本文,读者可以了解如何在字符串匹配过程中有效地避免重复比较。

算法核心,Next数组(模式串的最长前缀后缀表)。

KMP的思想就是,当匹配不正确时,模式串向后移动的距离为:

已匹配的字符串个数 - next[j]

而Next数组的算法起始也是递归的字符串匹配过程。

Impl:

 1 //Next数组计算
 2 void CalNext(const char* p, int* next)
 3 {
 4     int i = 0, j = -1;
 5     next[0] = -1;
 6     while (p[i] != '\0')
 7     {
 8         if (j < 0 || p[i] == p[j])
 9         {
10             i++, j++;
11             next[i] = j;
12         }
13         else
14             j = next[j];
15     }
16 }
17 
18 //利用Next数组的KMP
19 int KMPStr(char* haystack, const char* needle)
20 {
21     int res = 0;
22     int lenS = strlen(haystack);
23     int lenP = strlen(needle);
24     int i = 0, j = 0;
25     int* next = new int[lenP+1];
26     CalNext(needle, next);
27 
28     while (i < lenS && j < lenP)
29     {
30         if (j < 0 || haystack[i] == needle[j])
31         {
32             i++, j++;
33         }
34         else
35             j = next[j];
36 
37         if (j == lenP) {
38             j = next[j];
39             res++;
40         }
41     }
42 
43     delete[] next;
44     return res;
45 }
View Code

 

转载于:https://www.cnblogs.com/sheepsheep/p/4413605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值