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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43545471/article/details/102517483

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

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

int next[1000001]; // next数组
char str1[1000001]; // 主串
char str2[1000001]; // 模式串

void GetNextArr()
{
    int len1 = strlen(str1);
    int k = -1;
    int j = 0;
    next[0] = -1; // 初始化
    while(j < len1)
    {
        if (k == -1||str1[j] == str1[k])
        {
            k++;
            j++;
            next[j] = k;
        }
        else
            k = next[k];
    }
}

int Kmp()
{
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    int i = 0;
    int j = 0;
    while(i < len1&&j < len2)
    {
        if (j == -1||str1[i] == str2[j])
        {
            i++;
            j++;
        }
        else
        {
            j = next[j];
        }
    }
    if (j == len2)
    {
        return i-j+1;
    }
    else
        return -1;
}

int main()
{
    while(~scanf("%s %s", str1, str2))
    {
        GetNextArr();
        int pos = Kmp();
        printf("%d\n", pos);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43545471/article/details/102517483