Data Structure (8)

本文介绍了旧模式匹配算法的不足,重点讲解了Knuth-Morris-Pratt(KMP)算法的工作原理,包括next数组的计算和如何在字符串匹配中避免重复搜索。通过实例展示了如何使用C语言实现KMP算法,适用于字符串操作库和模式匹配优化。

KMP

Basic String Operations

The StrAssign、Strcopy、StrCompare、StrLength、Concat and SubString

String Operations Library (in C)

gets(str) //Input a string;

puts(str) //Output a string;

strcat(str1, str2) // string Concatenation;

strcpy(str1, str2, k) //String copy;

strcmp(str1, str2) //String comparision;

strlen(str) //Get the length of string

Pattern Matching algorithm

旧模式匹配算法:每次不匹配时,子串都从头重新匹配。效率很低

Basic match algorithm is inefficient

Knuth-Morris-Pratt (KMP Algorithms)

When dismatch happens, we don’t need to go back to first. We can use a next array to decide where to go back.

next[]: compare s[i] and t[j],if equals then continue comparing following items, else compare s[i] and t [ next[j] ], till end.

void  Get_next( SString T, int  &next[] )
{    j = 1 ;  // postfix pointer
     k = 0;   //prefix pointer
     next[1]=0;
    while ( j <= T[0] )
     {  if ( k == 0 || T[j] == T[k] ) 
             { ++j ;  ++k ;  next[j]=k; }
         else  
             k = next[k];  // k go back, then compare T[j] with T[ next[k] ]
     }// end while
}

For example:
a a b c a a a b c a d
0 1 2 1 1 2 3 3 4 5 6

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灰海宽松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值