1. 程式人生 > >SDUT-2772_數據結構實驗之串一:KMP簡單應用

SDUT-2772_數據結構實驗之串一:KMP簡單應用

strlen out else 結構 ddd http ref limit script

數據結構實驗之串一: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的題目之前,推薦先去看一下這篇博客

  • (原創)詳解KMP算法-孤~影(https://www.cnblogs.com/yjiyjige/p/3263858.html)
    這裏詳細講解了KMP的基礎,有了基礎再應付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簡單應用