字符匹配--KMP算法

 

bilibili视频

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

http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2561/pid/2772

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

解:

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

#define N 1000000+100

char st1[N];
char st2[N];
int next[N];

void getnext(int len2)
{
    int i=0, j=-1 ;
    next[0] = -1;
    while(i<len2)
    {
        if(j==-1 || st2[i]==st2[j])
        {
            i++;
            j++;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}

int kmp(int len1, int len2)
{
    int i=0;
    int j=0;
    while(i<len1 && j<len2)
    {
        if(j==-1 || st1[i]==st2[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if(j>=len2)
        return i-len2+1;
    else
        return -1;
}

int main()
{
    while(~scanf("%s", st1))
    {
        scanf("%s", st2);
        int len1 = strlen(st1);
        int len2 = strlen(st2);
        getnext(len2);
        int x = kmp(len1, len2);
        printf("%d\n", x);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/81357470
今日推荐