zoukankan      html  css  js  c++  java
  • SDUT-2772_数据结构实验之串一:KMP简单应用

    数据结构实验之串一: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的题目之前,推荐先去看一下这篇博客

    #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
    ",KMP());
        }
        return 0;
    }
    
  • 相关阅读:
    多表代换密码
    仿射变换
    LeetCode实战练习题目
    13.线性同余方程 扩展欧几里得算法
    12.扩展欧几里得算法
    11.快速幂求逆元
    10.快速幂
    9.筛法求欧拉函数
    8.欧拉函数
    7.最大公约数 欧几里得算法,也叫辗转相除法
  • 原文地址:https://www.cnblogs.com/luoxiaoyi/p/9759009.html
Copyright © 2011-2022 走看看