博客
关于我
【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/

    你可能感兴趣的文章
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>
    npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
    查看>>
    npm—小记
    查看>>