sdut_2125_数据结构实验之串二:字符串匹配

数据结构实验之串二:字符串匹配

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

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

Input

 输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2,string1和string2中保证不出现空格。(string1和string2大小不超过100字符)

Output

 对于每组输入数据,若string2是string1的子串,则输出"YES",否则输出"NO"。

Sample Input

abc
a
123456
45
abc
ddd

Sample Output

YES
YES
NO

Hint

Source

赵利强

代码如下

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

char str[102];
char st[1002];
int next[102];

void Find_next(int l)
{
    int i = 0;
    int j = -1;
    next[0] = -1;
    while(i < l)
    {
        if(j == -1 || str[i] == str[j])
        {
            i++; j++;
            next[i] = j;
        }
        else
            j = next[j];
    }
}

void kmp(int l, int s)
{
    int i = 0;
    int j = 0;
    while(i < s && j < l)
    {
        if(j == -1 || st[i] == str[j])
        {
            i++; j++;
        }
        else
            j = next[j];
    }
    if(j == l)
        printf("YES\n");
    else
        printf("NO\n");
}

int main()
{
    int l, s;
    while(~scanf("%s", st))
    {
        scanf("%s", str);
        l = strlen(str);
        s = strlen(st);
        Find_next(l);
        kmp(l,s);
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/strongerXiao/article/details/81456054