Manachor算法---求最长回文字串

来源:互联网 发布:申请淘宝网店的步骤 编辑:程序博客网 时间:2024/05/16 13:40

/****************************************************
*Given a string S, find the longest palindromic substring in S.
*You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
*
*S=”abadcacd” ,return “dcacd”
**************************************************************/

解析:普通的做法即在一个位置向两边扩,但是其时间复杂度为O(N^2),而使用manachor算法的时间复杂度降到了O(N),如下为次算法的解析。

关于最长回文字串的Manachor算法的详解:

这里写图片描述

AC代码

#include<iostream>#include<vector>#include<algorithm>#include<string>using namespace std;string preProcess(string s) {    int n = s.size();    string res = "^";    for (int i = 0; i < n; i++)        res += "#" + s.substr(i,1);    res += "#$";    return res;}string longestPalindrome(string s) {    string T = preProcess(s);    //等到预处理数组    int n = T.length();    int *P = new int[n];         //记录回文半径    int C = 0, pR = 0;    for (int i = 1; i < n - 1; i++) {        int i_mirror = 2 * C - i;    //这里的i_mirror为i关于最又边回文半径中心的镜像        P[i] = (pR > i) ? min(pR - i, P[i_mirror]) : 0;        while (T[i + 1 + P[i]] == T[i - 1 - P[i]])   //可以看到,这里做了很多的优化            P[i]++;        if (i + P[i] > pR) {       //当其超过了又边界pR时,需要更新它            C = i;                 //更新此时有边界的中心            pR = i + P[i];         //pR此时的位置        }    }    int maxLen = 0;    int centerIndex = 0;    for (int i = 1; i < n - 1; i++) {        if (P[i] > maxLen) {      //寻找最大的回文半径            maxLen = P[i];            centerIndex = i;        }    }    delete[] P;    return s.substr((centerIndex - 1 - maxLen) / 2, maxLen);}int main(){    string s = "ad12321b";    string s1 = "ad12321b123456654321";    cout << longestPalindrome(s1) << endl;  }
0 0
原创粉丝点击