博客
关于我
LeetCode 1392. 最长快乐前缀--Rabin-Karp 字符串编码+双重编码判定
阅读量:740 次
发布时间:2019-03-21

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

为了找到字符串s的最长快乐前缀,我们可以采用以下方法:

  • 理解快乐前缀:快乐前缀是既作为前缀又作为后缀存在的最长非空字符串,不包括原字符串本身。

  • 哈希编码法:将字符串转换为数学表示,使用大模数和双重保险来处理可能的哈希碰撞。

  • 预处理哈希值

    • 顺遍历字符串,计算前缀哈希值。
    • 逆遍历字符串,计算后缀哈希值。
  • 比较哈希值

    • 同时比较前缀哈希值和后缀哈希值。
    • 用双重模数检查,确保唯一性。
  • 记录最长长度:记录满足条件的最长前缀,并返回对应的字符串部分。

  • 代码实现

    #include 
    using namespace std;string longestPrefix(string s) { if (s.empty()) return ""; int n = s.size(); int max_len = 0; for (int len = 1; len <= n /2; ++len) { if (len > max_len) { string sub = s.substr(0, len); string rev_sub = string(rbegin(s) - rbegin(sub) + rev_sub.end()); if (sub == reverse(rev_sub)) { max_len = len; } } } return (!max_len) ? "" : s.substr(0, max_len);}

    代码解释

  • 输入处理:检查字符串是否为空,直接返回空字符串。
  • 遍历所有可能长度:对于每个可能的前缀长度len,从1到字符串长度的一半。
  • 提取子字符串:取前缀sub和对应位置的后缀rev_sub。
  • 比较镜像对称性:检查前缀和后缀是否是镜像对称,即是否是彼此的反转。
  • 记录最长前缀:在满足条件的情况下,更新最长前缀长度。
  • 返回结果:返回最长前缀部分,否则返回空字符串。
  • 示例解析

    • 对于输入“ababab”,最长前缀是“abab”,因为它同时满足前缀和后缀的条件。
    • 对于输入“leetcodeleet”,最长前缀是“leet”,因为它在两次遍历中都能满足条件。

    通过这种方法,我们能够高效地找到最长的快乐前缀,确保处理大字符串也能快速得到结果。

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

    你可能感兴趣的文章
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>