sdut 2125串结构练习--字符串匹配【两种KMP算法】

串结构练习——字符串匹配

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2125

题目描述

  给定两个字符串string1和string2,判断string2是否为string1的子串。
 

输入

 输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。
 

输出

 对于每组输入数据,若string2是string1的子串,则输出"YES",否则输出"NO"。
 

示例输入

abc
a
123456
45
abc
ddd

示例输出

YES
YES
NO

提示

代码:

 1 #include<string.h>
 2 #include<iostream>
 3 using namespace std;
 4 char S[100],T[100];
 5 int s,t,next[100],nextval[100];
 6 void get_next(char T[],int next[]);//对应模式匹配算法一next函数值
 7 void get_nextval(char T[],int nextval[]);//对应模式匹配算法二nextval函数值
 8 int Index_KMP(char S[],char T[],int pos);//模式匹配算法一
 9 int Index_KMP2(char S[],char T[],int pos);//模式匹配算法二
10 int main()
11 {
12     while(cin>>S>>T)
13     {
14         memset(next,0,sizeof(next));
15         int i;
16         s=strlen(S);
17         t=strlen(T);
18         for(i=s;i>=1;i--)
19             S[i]=S[i-1];
20         S[s+1]='\0';
21         for(i=t;i>=1;i--)
22             T[i]=T[i-1];
23         T[t+1]='\0';
24         //get_next(T,next);
25         get_nextval(T,nextval);
26         //int flag=Index_KMP(S,T,1);//通过这里可以验证两个算法
27         int flag=Index_KMP2(S,T,1);
28         //for(i=1;i<=t;i++)
29           //  cout<<nextval[i]<<" ";
30         //cout<<endl;
31         if(flag==0)cout<<"NO"<<endl;
32         else cout<<"YES"<<endl;
33     }
34     return 0;
35 }
36 void get_next(char T[],int next[])//对应模式匹配算法一next函数值
37 {
38     int i=1,j=0;
39     next[1]=0;
40     while(i<t)
41     {
42         if(j==0||T[i]==T[j])
43         {
44             ++i;
45             ++j;
46             next[i]=j;
47         }
48         else j=next[j];
49     }
50 }
51 void get_nextval(char T[],int nextval[])//对应模式匹配算法二nextval函数值
52 {
53     int i=1,j=0;
54     nextval[1]=0;
55     while(i<t)
56     {
57         if(j==0||T[i]==T[j])
58         {
59             ++i;
60             ++j;
61             if(T[i]!=T[j])
62                 nextval[i]=j;
63             else
64                 nextval[i]=nextval[j];
65         }
66         else
67             j=nextval[j];
68     }
69 }
70 int Index_KMP(char S[],char T[],int pos)//模式匹配算法一
71 {
72     int i=pos,j=1;
73     while(i<=s&&j<=t)
74     {
75         if(j==0||S[i]==T[j])
76         {
77             ++i;
78             ++j;
79         }
80         else j=next[j];
81     }
82     if(j>t)return i-t;
83     else return 0;
84 }
85 int Index_KMP2(char S[],char T[],int pos)//模式匹配算法二
86 {
87     int i=pos,j=1;
88     while(i<=s&&j<=t)
89     {
90         if(j==0||S[i]==T[j])
91         {
92             ++i;
93             ++j;
94         }
95         else j=nextval[j];
96     }
97     if(j>t)return i-t;
98     else return 0;
99 }
View Code

 

posted @ 2013-12-19 15:02  狂盗一枝梅  阅读(342)  评论(0编辑  收藏  举报