-
题目
题目描述:给定字符串s,求解含有两个s的最短字符串。例如"ababa"含有两个"aba" -
解题思路:
利用kmp求解字符串的最后一个字符的下一个字符的next[]
处理成最大前缀和最大后缀能重复多少,向尾部添加从最大相同前缀后开始到结尾的子串 -
代码:
#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;

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

被折叠的 条评论
为什么被折叠?



