数据结构实验之串一:KMP简单应用

6 篇文章 0 订阅

数据结构实验之串一:KMP简单应用

Time Limit: 1000MS  Memory Limit: 65536KB
Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
 输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
 对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Example Input
abc
a
123456
45
abc
ddd
Example Output
1
4
-1

思路:裸的KMP,直接套板子

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int MAXN=1000000+10;
char a[MAXN],b[MAXN];
int next[MAXN];
int l1,l2;
void get_next()
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<l2)
    {
        if(j==-1||b[i]==b[j])next[++i]=++j;
        else j=next[j];
    }
}
int kmp()
{
    int i=0,j=0;
    while(i<l1)
    {
        if(j==-1||a[i]==b[j])
        {
            ++i;
            ++j;
        }
        else j=next[j];
        if(j==l2)return i+1-l2;
    }
    return -1;
}

int main()
{
    while(~scanf("%s%s",a,b))
    {
        l1=strlen(a);
        l2=strlen(b);
        get_next();
        printf("%d\n",kmp());
    }
    return 0;
}


/***************************************************
Result: Accepted
Take time: 108ms
Take Memory: 1536KB
Submit time: 2016-10-25 16:30:22
****************************************************/





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值