zoukankan      html  css  js  c++  java
  • SDUT 2125 数据结构实验之串二:字符串匹配

     

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

    Time Limit: 1000 ms Memory Limit: 65536 KiB

    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

    提示:本题和上一题做法几乎一模一杨,依然可以用到strstr,这里只给出KMP的代码,strstr可以自己试着A一下。

    代码实现如下(gcc):
    #include<stdio.h>
    #include<string.h>
    
    char s1[1000010], s2[1000010];
    int next[1000010];
    
    void getnext()
    {
        int len = strlen(s2);
        int i = 0, j = -1;
        next[0] = -1;
        while(i < len)
        {
            if(j == -1 || s2[i] == s2[j])
            {
                i++;
                j++;
                if(s2[i] != s2[j]) next[i] = j;
                else next[i] = next[j];
            }
            else j = next[j];
        }
    }
    int kmp()
    {
        int i = 0, j = 0;
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        while(i < len1 && j < len2)
        {
            if(j == -1 || s1[i] == s2[j])
            {
                i++;
                j++;
            }
            else
            {
                j = next[j];
            }
        }
        if(j >= len2)
        {
            printf("YES
    ");
        }
        else printf("NO
    ");
        return 0;
    }
    int main()
    {
        while(~scanf("%s", s1))
        {
            scanf("%s", s2);
            getnext();
            kmp();
        }
        return 0;
    }
    
    
    
    /***************************************************
    Result: Accepted
    Take time: 0ms
    Take Memory: 160KB
    ****************************************************/


  • 相关阅读:
    线段的类
    计算三角形的类
    关于狗的类
    [poj2234] Matches Game
    bzoj[2655] calc
    拉格朗日插值和牛顿插值 菜鸟教程
    NOI模拟赛(3.15) sequence(序列)
    NOI模拟赛(3.13)Hike (远行)
    二分图讲解
    NOI模拟赛(3.8)Problem B
  • 原文地址:https://www.cnblogs.com/jkxsz2333/p/9492325.html
Copyright © 2011-2022 走看看