串的模式匹配

本文详细介绍了三种常用的字符串匹配算法:BF算法、KMP算法及next和nextval算法的实现过程。BF算法通过逐字符比较实现匹配;KMP算法利用部分匹配表提高效率;next和nextval算法用于预处理模式串,生成偏移表。

1.BF模式匹配算法:

 1 int Index(SString S, int pos, SString T)
 2 {
 3     int i = pos, j = 1;
 4     while (i < S.len&&j < T.len)
 5     {
 6         if (S.ch[j] == T.ch[j])
 7         {
 8             i++;
 9             j++;
10         }
11         else
12         {
13             i = i - j + 2;
14             j = 1;
15         }
16     }
17     if (j > T.len) return i - T.len;
18     else return 0;
19 }

 2.KMP算法

 1 int Index_KMP(SString S,int pos,SString T)
 2 {
 3     int i = pos, j = 1;
 4     while (i <= S.len&&j <= T.len)
 5     {
 6         if (j == 0 || S.ch[i] == T.ch[j])
 7         {
 8             ++i;
 9             ++j;
10         }
11         else j = next[j];
12     }
13     if (j > T.len) return i - T.len;
14     else return 0;
15 }

3.next算法

 1 void Get_Next(SString T, int next[])
 2 {
 3     int j = 1, k = 0;
 4     next[1] = 0;
 5     while (j < T.len)
 6     {
 7         if (k == 0 || T.ch[j] == T.ch[k])
 8         {
 9             ++j;
10             ++k;
11             next[j] = k;
12         }
13         else k = next[k];
14     }
15 }

4.nextval算法

 1 void Get_NextVal(SString T, int next[], int nextval[])
 2 {
 3     int j = 1, k = 0;
 4     Get_Next(T,next);  //获得next的值
 5     nextval[1] = 0;
 6     while (j < T.len)
 7     {
 8         k = next[j];
 9         if (T.ch[j] == T.ch[k])
10             nextval[j] = nextval[k];
11         else
12             nextval[j] = next[j];
13         j++;
14     }
15 }

 

转载于:https://www.cnblogs.com/xyzyj/p/6639803.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值