码迷,mamicode.com
首页 > 其他好文 > 详细

【回文字符串】 最长回文子串O(N) Manacher算法

时间:2014-09-20 19:44:09      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   ar   for   div   art   sp   

原理讲的清晰:Manacher‘s ALGORITHM: O(n)时间求字符串的最长回文子串

注意:

①动态生命P[]和newStr数组后,不要忘记delete[] //其实这是基本的编码习惯

②最终返回结果是P[i]-1

下面是自己写的Manacher函数

int manacher(char *src){
    int srcLen=strlen(src);
    int len=2*srcLen+2;
    char *newStr=new char[len];//还是+3??要不要给\0留个位置??不用
    int *P=new int[len];
    int i,rst=0;
    //处理字符串
    newStr[0]=$;
    newStr[1]=#;
    for(i=0;i<srcLen;i++){
        newStr[2*i+2]=src[i];
        newStr[2*i+3]=#;
    }

    //关键步骤:求P[i]
    int id=0;
    int mx=0;
    P[0]=1;
    for(i=1;i<len;i++){
        if(mx>i)
            P[i]= MIN(mx-i , P[2*id-i]);
        else
            P[i]=1;
        while(newStr[i+P[i]] == newStr[i-P[i]])
            P[i]++;//据说这一步永远不会成立
        //更新id和mx
        if(P[i]+i > mx){
            id=i;
            mx=P[i]+i;
        }
    }

    //找到P[i]中最大值,注意最终返回的结果是P[i]-1
    for(i=0;i<len;i++)
        if(rst<P[i])
            rst=P[i];

    delete[] P;
    delete[] newStr;
    return rst-1;    
}

 

参考代码:http://blog.csdn.net/ggggiqnypgjg/article/details/6645840 用定长的char数组

http://blog.csdn.net/bruce_zeng/article/details/8629572 new动态声明后没有delete

http://blog.csdn.net/pi9nc/article/details/9251455

【回文字符串】 最长回文子串O(N) Manacher算法

标签:style   blog   http   color   ar   for   div   art   sp   

原文地址:http://www.cnblogs.com/zhangXH/p/3983504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!