• 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;
    }


  • 相关阅读:
    jQuery里使用setinterval
    关于java以及JavaScript或者更多的语言中Data类的问题
    重置input checked
    利用CSS变量实现悬浮效果
    vue 可编辑表格组件
    js 可拉伸表格
    vue 自定义拖拽指令
    vue 表格导出excel
    vue 侧边导航栏递归显示
    RUP(Rational Unified Process)统一软件过程概述
  • 原文地址:https://www.cnblogs.com/Genesis2018/p/9079874.html
Copyright © 2020-2023  润新知