飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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 <stdlib.h>
#include <string.h>

int next[1000000];
char str[1000000];
char substr[1000000];

void getnext()
{
    int i=0,j=-1;
    next[0]=-1;
    while(substr[i]!='\0')
    {
        if(j==-1||substr[i]==substr[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
            j=next[j];
    }
}

void kmp()
{
    int i=0,j=0;
    int len1=strlen(str);
    int len2=strlen(substr);
    while(i<len1&&j<len2)
    {
        if(j==-1||str[i]==substr[j])
        {
            i++;
            j++;
        }
        else
        {
            j=next[j];
        }
    }
        if(j>=len2)
        {
            printf("%d\n",i-len2+1);
        }
        else
        {
            printf("-1\n");
        }
}

int main()
{
    while(gets(str))
    {
        gets(substr);
        getnext();
        kmp();
    }
    return 0;
}

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

char a[1000001];
char b[1000001];
int  next[1000001];

void getnext()
{
    int i=0;
    int j=-1;
    next[0]=-1;
    while(a[i]!='\0')
    {
        if(j==-1||a[i]==b[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
        {
            j=next[j];
        }
    }
}//三化一循环,循环内部两条件。

void KMP()
{
    int i=0;
    int j=0;
    int len1=strlen(a);
    int len2=strlen(b);
    while(i<len1&&j<len2)
    {
        if(j==-1||a[i]==b[j])
        {
            i++;
            j++;
        }
        else
        {
            j=next[j];
        }
    }
    if(j==len2)
    {
        printf("%d\n",i-len2+1);
    }
    else
    {
        printf("-1\n");
    }
}//四化一循环,循环内部两条件,循环完了if else来判断

int main()
{
    while(scanf("%s %s",a,b)!=EOF)
    {
        getnext();
        KMP();
    }
    return 0;
}

posted on 2018-11-08 14:18  飞行的猪哼哼  阅读(26)  评论(0)    收藏  举报