o(n)的时间复杂判断回文数

class CManacher:public CTest
    {
        string GetManacher(const string str)
        {
            string strTmp;
             string result="";
            int *p=new int[2*str.size()+1];
            int i;
            strTmp+='#';
            int j=1;
            for(i=0;i<str.size();i++)
            {
                strTmp+=str[i];
                strTmp+='#';
            }
            int id=0,max=0;
            p[0]=1;
            cout<<strTmp.c_str()<<endl;
            bool search=false;
            for(i=1;i<strTmp.size();i++)
            {
                j=2*id-i;
                if(j>=0)
                {
                    if(i<max)
                    {
                        if(p[j]<=max-i+1)
                        {
                            p[i]=p[j];
                        }
                        else
                        {
                            p[i]=max-i+1;
                            search=true;
                        }
                    }
                    else
                    {
                        p[i]=1;
                        search=true;
                    }
                }
                else
                {
                    p[i]=1;
                    search=true;
                }
                if(search)
                {
                    search=false;
                    while(strTmp[i-p[i]]==strTmp[i+p[i]])p[i]++;
                }
                if(i+p[i]-1>max)
                {
                    max=i+p[i]-1;
                    id=i;
                }

            }
            max=0;
            id=0;
            for(i=0;i<strTmp.size();i++)
            {
                if(p[i]>max)
                {
                    max=p[i];
                    id=i;
                }
            }

       
            for(int i=id-p[id]+1;i<=id+p[id]-1;i++)
            {

                if(strTmp[i]!='#')
                {
                    result+=strTmp[i];
                }
            }
            //cout<<result.c_str()<<endl;
            delete []p;
            return result;
        }
    public:
        void Test()
        {
             string str = "12212321";
             string res=GetManacher(str);
             cout<<res.c_str()<<endl;
        }
    };
};

 

posted on 2013-08-26 19:33  dyc0113  阅读(225)  评论(0编辑  收藏  举报

导航