kmp的应用1——京东2018测试开发工程师笔试题

本文介绍了一种求解含有两个给定字符串的最短字符串的算法。通过使用KMP算法计算字符串的next数组,找到最大前缀和后缀的重复长度,从而高效地构造出目标字符串。代码示例展示了如何实现这一算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 题目
    题目描述:给定字符串s,求解含有两个s的最短字符串。例如"ababa"含有两个"aba"

  2. 解题思路:
    利用kmp求解字符串的最后一个字符的下一个字符的next[]
    处理成最大前缀和最大后缀能重复多少,向尾部添加从最大相同前缀后开始到结尾的子串

  3. 代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
using namespace std;


int Get_EndNext_Length(string str2)
{
    int len = str2.length();
    vector<int> next(len+1);
    next[0] = -1;
    next[1] = 0;

    int pos = 2;
    int cn = 0;
    while(pos < next.size())
    {
        if(str2[pos-1] == str2[cn]){
            next[pos++] = ++cn;
        }else if(cn > 0){
            cn = next[cn];
        }else{
            next[pos++] = 0;
        }
    }
    return next[next.size()-1]; //next数组的最后一个值
}

string Answer_Of_Shortest_Twice(string str1)
{
    int len = str1.length();
    if(len == 0 || str1.empty()) return "";
    else if(len == 1){
        return str1+str1;
    }else if(str1.length() == 2){
        return str1[0] == str1[1] ? str1 + str1.substr(1) : str1+str1;
    }else{
        return str1 + str1.substr(Get_EndNext_Length(str1));
    }
}

int main(int argc, char const *argv[])
{
    string s1 = "a";
    cout<<Answer_Of_Shortest_Twice(s1)<<endl;

    string s2 = "ababa";
    cout<<Answer_Of_Shortest_Twice(s2)<<endl;

    string s3 = "12312";
    cout<<Answer_Of_Shortest_Twice(s3)<<endl;

    string s4 = "abcabc";
    cout<<Answer_Of_Shortest_Twice(s4)<<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值