码迷,mamicode.com
首页 > 其他好文 > 详细

SDUT-2772_数据结构实验之串一:KMP简单应用

时间:2018-10-09 11:01:10      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:str   www.   get   ||   ng2   print   kmp   sample   mit   

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

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

Input

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

Output

对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。

Sample Input

abc
a
123456
45
abc
ddd

Sample Output

1
4
-1

Hint

Source

cjx

在做KMP的题目之前,推荐先去看一下这篇博客

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int Next[1000050];
char s1[1000050],s2[1000050];

void get_next()//求next数组。
{
    int i,j,m;
    m = strlen(s2);
    i = 0;
    j = -1;
    Next[0] = -1;
    while(i<m)
    {
        if(j==-1||s2[i]==s2[j])
        {
            i++;
            j++;
            Next[i] = j;
        }
        else
            j = Next[j];
    }
}

int KMP()//KMP算法
{
    int i,j,n,m;
    n = strlen(s1);
    m = strlen(s2);
    get_next();
    i = j = 0;
    while(i<n)
    {
        if(j==-1||s1[i]==s2[j])
        {
            i++;
            j++;
        }
        else
            j = Next[j];
        if(j==m)
            return i - j + 1;
    }
    return -1;
}

int main()
{
    while(scanf("%s%s",s1,s2)!=EOF)
    {
        printf("%d\n",KMP());
    }
    return 0;
}

SDUT-2772_数据结构实验之串一:KMP简单应用

标签:str   www.   get   ||   ng2   print   kmp   sample   mit   

原文地址:https://www.cnblogs.com/luoxiaoyi/p/9759009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!