SDUT OJ数据结构实验之串二:字符串匹配

本文介绍了一种基于KMP算法的字符串匹配方法,并提供了详细的代码实现。通过对给定的两个字符串进行匹配判断,能够有效地确定一个字符串是否为另一个字符串的子串。

数据结构实验之串二:字符串匹配

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

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

 

Input

 输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)

 

Output

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

 

Sample Input

abc
a
123456
45
abc
ddd

Sample Output

YES
YES
NO

Hint

 

Source

赵利强

#include <stdio.h>
#include <string.h>
int next[101];
void set(char ch1[])
{
    int i=0,i1=-1,len;
    len=strlen(ch1);
    next[i]=i1;
    while(i<len)
    {
        if(i1==-1||ch1[i]==ch1[i1])
        {
            i++;
            i1++;
            next[i]=i1;
        }
        else i1=next[i1];
    }
}
int kmp(char ch[],char ch1[])
{
    int i=0,i1=0,len,len1;
    len=strlen(ch);
    len1=strlen(ch1);
    while(i<len&&i1<len1)
    {
    if(i1==-1||ch[i]==ch1[i1])
    {
        i++;
        i1++;
    }
    else i1=next[i1];
    }
    if(i1==len1)
        return i-len1+1;
    else return -1;
}
int main()
{
 char ch[101],ch1[101];
 while(scanf("%s",ch)!=EOF)
 {
     scanf("%s",ch1);
     set(ch1);
     if(kmp(ch,ch1)!=-1)printf("YES\n");
     else printf("NO\n");
 }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值