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

    你可能感兴趣的文章
    NLP的神经网络训练的新模式
    查看>>
    NLP采用Bert进行简单文本情感分类
    查看>>
    NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>