#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void findBMstr(string str0){
string str;
str += "$#";
int n=str0.size();
for(int i = 0; i < n; i++){
str += str0[i];
str += "#";
}
int len=str.size();
int *p = new int[len + 1];
memset(p, 0, sizeof(p));
int mx = 0, id = 0;
for(int i = 1; i <= len; i++){
if(mx > i){
p[i] = (p[2*id - i] < (mx - i) ? p[2*id - i] : (mx - i));
}
else{
p[i] = 1;
}
while(str[i - p[i]] == str[i + p[i]])
p[i]++;
if(i + p[i] > mx){
mx = i + p[i];
id = i;
}
}
int Max = 0, ii;
for(int i = 1; i < len; i++){
if(p[i] > Max){
ii = i;
Max = p[i];
}
}
Max--;
int s = ii - Max ;
int e = ii + Max;
for(int i = s; i <= e; i++){
if(str[i] != '#'){
cout << str[i];
}
}
cout << endl;
delete p;
}
int main()
{
string str;
cin>>str;
findBMstr(str);
return 0;
}
马拉车算法模板
最新推荐文章于 2022-04-03 21:58:21 发布
本文介绍了一个基于Boyer-Moore算法的字符串查找实现。通过预处理字符串并利用字符匹配特性来提高搜索效率。该算法使用了C++语言进行编码,并详细展示了如何通过构造特殊字符串形式和动态调整匹配位置来优化查找过程。

456

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



