/*寻找字符串中的最长回文串,马拉车算法*/
#include<string>
#include<vector>
#include<iostream>
using namespace std;
class PreHandle
{
public:
PreHandle(string arr);
~PreHandle();
void findLongestPlalindromeString();
inline string preHandleString();
private:
string str;
};
PreHandle::PreHandle(string arr)
{
str = arr;
}
PreHandle::~PreHandle()
{
str.clear();
}
//预处理字符串,在字符之间加‘#’
inline string PreHandle::preHandleString()
{
/*string p;
p.append(1,'#');
for (int i = 0; i < str.length(); i++)
{
p.append(1,str.at(i));
p.append(1, '#');
}
str = p;
p.clear();
cout << "处理后的字符串:"<<str<<endl;
return str;*/
}
//寻找最长回文子串
void PreHandle::findLongestPlalindromeString()
{
//先预处理字符串
string p = preHandleString();
//处理后的字符串长度
int len = str.length();
//记录回文串的右边界
int rightSide = 0;
//记录右边界对应的回文中心的位置
int rightSideCenter = 0;
//保存扩展后每个字符为中心的回文长度的一半,向下取整,即为字符串的最长回文长度
int *halfLenArr = new int[len];
for (int i = 0; i < len; i++)
{
halfLenArr[i] = 0;
}
//最长回文长度
int longestArr = 0;
//记录最长回文中心的位置
int center = 0;
for (int i = 0; i < len; ++i)
{
//是否需要扩展
bool flag = true;
//在右边界的覆盖范围之内
if (i < rightSide)
{
//找到对称位置,判断以该字符为中心的回文串的长度
int leftCenter = 2 * rightSideCenter - i;
halfLenArr[i] = halfLenArr[leftCenter];
//如果回文串超过了右边界
if (i + halfLenArr[i] > rightSide)
{
halfLenArr[i] = rightSide - i;//在内部时的回文长度
}
//如果i位置的回文长度在右边界内部,不需要拓展
if (i + halfLenArr[i] < rightSide)
{
flag = false;
}
}
//中心扩展
if (flag)
{
while (i - halfLenArr[i] - 1 >= 0 && i + halfLenArr[i] + 1 < len)
{
if (str.at(i - halfLenArr[i] - 1) == str.at(i + halfLenArr[i] + 1))
{
halfLenArr[i]++;
}
else
{
break;
}
}
//更新右边界及中心
rightSide = i + halfLenArr[i];
rightSideCenter = i;
//记录最长回文串
if (halfLenArr[i] > longestArr)
{
center = i;
longestArr = halfLenArr[i];
}
else
{
continue;
}
}
}
//处理添加的'#'
string a;
for (int k = center - longestArr +1; k < center + longestArr+1; k+=2)
{
a.append(1, str.at(k));
}
cout << "最长回文串:"<<a << endl;
//cout << str << endl;
a.clear();
delete[]halfLenArr;
}
int main()
{
cout << "原字符串:" << "adcds" << endl;
PreHandle s1("adcds");
s1.findLongestPlalindromeString();
cout << "原字符串:" << "cabcdcbae" << endl;
PreHandle s2("cabcdcbae");
s2.findLongestPlalindromeString();
return 0;
}