zoukankan      html  css  js  c++  java
  • 问题 1690: 算法4-7:KMP算法中的模式串移动数组

    题目链接:https://www.dotcpp.com/oj/problem1690.html

    题目描述
    字符串的子串定位称为模式匹配,模式匹配可以有多种方法。简单的算法可以使用两重嵌套循环,时间复杂度为母串与子串长度的乘积。而KMP算法相对来说在时间复杂度上要好得多,为母串与子串长度的和。但其算符比较难以理解。
    在KMP算法中,使用到了一个next数组。这个数组就是在比较失配时母串指针不必回溯,而子串指针移动相应位置即可。我们给出书中next数组的算式表示以及算法,请你实现之。
    图1:next数组的算式表示
    图2:next数组的算法表示
    输入

    一个模式串,仅由英文小写字母组成。长度不大于100。

    输出

    输出模式串对应的移动数组next。每个整数后跟一个空格。

    样例输入
    abaabcac
    样例输出
    0 1 1 2 2 3 1 2 
     1 #include <iostream>
     2 #include <algorithm>
     3 #include <string>
     4 #include <cstring>
     5 using namespace std;
     6 string str;
     7 int nex[100];
     8 int len;
     9 void get_next()
    10 {
    11     int i=0,j=-1;
    12     nex[0]=-1;
    13     while(i<len){
    14         if(j==-1||str[i]==str[j]){
    15             i++;
    16             j++;
    17             nex[i]=j;
    18         }
    19         else
    20             j=nex[j];
    21     }
    22 }
    23 int main()
    24 {
    25     while(cin>>str){
    26         len=str.length();
    27         get_next();
    28         for(int i=0;i<len;i++){
    29             cout<<nex[i]+1<<" ";
    30         }
    31         cout<<endl;
    32     }
    33     return 0;
    34 }
  • 相关阅读:
    Leetcode Power of Two
    Leetcode Reverse Integer
    Leetcode Add Digits
    Leetcode Roman to Integer
    Python 函数的定义语法
    Python 函数的三种定义方式
    Python 函数的定义与调用
    Python 函数分类
    Python 为什么要使用函数
    Python 文件的二进制读写
  • 原文地址:https://www.cnblogs.com/wydxry/p/10748457.html
Copyright © 2011-2022 走看看