zoukankan      html  css  js  c++  java
  • 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;
            }
        };
    };
  • 相关阅读:
    Js变量类型
    前端面试题HTML
    AP聚类
    锚点
    html
    Active Learning主动学习
    z-index
    position
    学习笔记_卷积神经网络
    学习笔记_深度学习的数学基础
  • 原文地址:https://www.cnblogs.com/dyc0113/p/3283399.html
Copyright © 2011-2022 走看看