zoukankan      html  css  js  c++  java
  • KMP简单应用

    KMP简单应用

    题目描述

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

    输入

     输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。

    输出

     对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。

    示例输入

    abc
    a
    123456
    45
    abc
    ddd
    

    示例输出

    1
    4
    -1
    #include<stdio.h>
    #include<string.h>
    #define inf 1000001
    char str1[inf], str2[inf];
    int next[inf];
    void GetNext(char* p,int next[])
    {
        int pLen = strlen(p);
        next[0] = -1;
        int k = -1;
        int j = 0;
        while (j < pLen - 1)
        {
            if (k == -1 || p[j] == p[k])
            {
                ++k;
                ++j;
                next[j] = k;
            }
            else
            {
                k = next[k];
            }
        }
    }
    int KmpSearch(char* s, char* p)
    {
        int i = 0;
        int j = 0;
        int sLen = strlen(s);
        int pLen = strlen(p);
        while (i < sLen && j < pLen)
        {
            if (j == -1 || s[i] == p[j])
            {
                i++;
                j++;
            }
            else
                j = next[j];
        }
        if (j == pLen)
            return i - j + 1;
        else
            return -1;
    }
    int main(){
        while(scanf("%s%s", &str1, &str2) != EOF ){
            GetNext(str2, next);
            printf("%d
    ", KmpSearch(str1, str2));
        }
        return 0;
    }


  • 相关阅读:
    妹妹
    小猴和北极熊
    盛趣->盛大
    运维
    操之过急
    修马路
    博人传
    醉酒
    【跨域】SpringBoot跨域,拦截器中,第一次获取的请求头为NULL,发送两次请求的处理方式
    【Linux】Linux安装Tomcat
  • 原文地址:https://www.cnblogs.com/Genesis2018/p/9079874.html
Copyright © 2011-2022 走看看