hdu 1711 Number Sequence

本文介绍了一种高效的字符串匹配算法——KMP算法,并通过C++代码实现了在母链中查找子链位置的功能。该算法避免了传统模式匹配中目标串指针的回溯,提高了搜索效率。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711

题目大意:在母链中找到子链的位置,输出开始的位置。

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int lens,lenc,next[1000005],str[1000005],ch[1000005];
 5 
 6 int get_next()
 7 {
 8     int i=0,j=-1;
 9     next[0]=-1;
10     while (i<lens)
11     {
12         if (j==-1||str[i]==str[j])
13         {
14             i++;
15             j++;
16             next[i]=j;
17         }
18         else
19             j=next[j];
20     }
21 }
22 
23 int kmp()
24 {
25     int i=0,j=0;
26     get_next();
27     while (i<lenc)
28     {
29         if(j==-1||str[j]==ch[i])
30         {
31             i++;
32             j++;
33         }
34         else
35             j=next[j];
36         if (j==lens)
37             return i-j+1;
38 
39     }
40     return -1;
41 }
42 
43 int main ()
44 {
45     int t;
46     scanf("%d",&t);
47     while (t--)
48     {
49         //int n,m;
50         scanf("%d%d",&lenc,&lens);
51         for (int i=0; i<lenc; i++)
52             scanf("%d",&ch[i]);
53         for (int j=0; j<lens; j++)
54             scanf("%d",&str[j]);
55         printf ("%d\n",kmp());
56     }
57     return 0;
58 }

 

转载于:https://www.cnblogs.com/qq-star/p/3890560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值