博客
关于我
【KMP】重复子串
阅读量:697 次
发布时间:2019-03-14

本文共 990 字,大约阅读时间需要 3 分钟。

对于每个字符串,我们可以使用KMP算法来计算前缀函数数组。前缀函数数组的最后一个值p[len]可以帮助我们确定最大的重复子串的长度。如果p[len]不为0,那么这个长度就是最大的周期长度。重复次数就是整个字符串的长度除以周期长度。

KMP算法的步骤如下:

  • 初始化前缀函数数组p,长度为n+1,其中n是字符串的长度。
  • 遍历字符串,计算前缀函数数组中每个元素p[i]。
  • 计算周期长度为n - p[n]。
  • 如果n能被周期长度整除,那么重复次数就是n /周期长度;否则,重复次数为1。
  • 通过这种方法,我们可以高效地找到每个字符串最多能被重复连接的子串的数量。

    代码如下:

    #include 
    #include
    #include
    using namespace std;int main() { char s[10000005]; int len; scanf("%s", s + 1); len = strlen(s + 1); while (len != 1 || s[1] != '.') { int j = 0; for (int i = 2; i <= len; ++i) { while (j > 0 && s[i] != s[j + 1]) j = p[j]; if (s[i] == s[j + 1]) ++j; p[i] = j; } if (len % (len - p[len]) == 0) printf("%d\n", len / (len - p[len])); else printf("1\n"); scanf("%s", s + 1); len = strlen(s + 1); } return 0;}

    这个代码使用了KMP算法来计算前缀函数数组,从而确定最大的重复子串的周期长度和重复次数。通过这种方法,我们可以高效地解决问题,确保代码在处理长字符串时也能快速运行。

    转载地址:http://bbzlz.baihongyu.com/

    你可能感兴趣的文章
    Objective-C实现cocktail shaker sort鸡尾酒排序算法(附完整源码)
    查看>>
    Objective-C实现cocktailShakerSort鸡尾酒排序算法(附完整源码)
    查看>>
    Objective-C实现CoinChange硬币兑换问题算法(附完整源码)
    查看>>
    Objective-C实现collatz sequence考拉兹序列算法(附完整源码)
    查看>>
    Objective-C实现Collatz 序列算法(附完整源码)
    查看>>
    Objective-C实现comb sort梳状排序算法(附完整源码)
    查看>>
    Objective-C实现combinationSum组合和算法(附完整源码)
    查看>>
    Objective-C实现combinations排列组合算法(附完整源码)
    查看>>
    Objective-C实现combine With Repetitions结合重复算法(附完整源码)
    查看>>
    Objective-C实现combine Without Repetitions不重复地结合算法(附完整源码)
    查看>>
    Objective-C实现conjugate gradient共轭梯度算法(附完整源码)
    查看>>
    Objective-C实现connected components连通分量算法(附完整源码)
    查看>>
    Objective-C实现Connected Components连通分量算法(附完整源码)
    查看>>
    Objective-C实现Convex hull凸包问题算法(附完整源码)
    查看>>
    Objective-C实现convolution neural network卷积神经网络算法(附完整源码)
    查看>>
    Objective-C实现convolve卷积算法(附完整源码)
    查看>>
    Objective-C实现coulombs law库仑定律算法(附完整源码)
    查看>>
    Objective-C实现counting sort计数排序算法(附完整源码)
    查看>>
    Objective-C实现countSetBits设置位的数量算法(附完整源码)
    查看>>
    Objective-C实现currency converter货币换算算法(附完整源码)
    查看>>