美文网首页
最长回文串子串 渣渣版

最长回文串子串 渣渣版

作者: 三三At你 | 来源:发表于2017-05-11 21:35 被阅读0次
    #include<iostream>  
    #include<cstdio>  
    #include<string>  
    using namespace std;  
      
    int main()  
    {  
        int n,l,r,pos,maxlen;  
        string str;  
        cin>>n;  
        while(n--)  
        {  
            cin>>str;  
            for(int i=0;i<=str.length();i+=2)  
                str.insert(i,"#");  
            maxlen = 0;  
            for(pos = (str.length()-1)/2; pos >=0 ; pos--)  
            {  
                l = pos - 1;  
                r = pos + 1;  
                while(l>=0&&r<str.length()&&str[l]==str[r])  
                {  
                    l--;  
                    r++;  
                }  
                if(r-l-1>maxlen)  
                    maxlen = r-l-1;  
                if(maxlen == 2*pos+1)  
                    break;  
            }  
            for(pos = (str.length()-1)/2; pos <str.length() ; pos++)  
            {  
                l = pos - 1;  
                r = pos + 1;  
                while(l>=0&&r<str.length()&&str[l]==str[r])  
                {  
                    l--;  
                    r++;  
                }  
                if(r-l-1>maxlen)  
                    maxlen = r-l-1;  
                if(maxlen == 2*((str.length()-1)-pos)+1)  
                    break;  
            }  
            cout<<(maxlen%2?maxlen/2:maxlen/2-1)<<endl;  
      
        }  
    }  
    
    #include<iostream>  
    #include<cstdio>  
    #include<string>  
    using namespace std;  
      
    int clac(char *str, int p, int len){  
        int l = p-1, r = p+1;  
        int k = 1;  
        while(l>=0&&r<len&&str[l--]==str[r++])  
            k+=2;  
        return k;  
    }  
      
    int init(const char *str,int len)  
    {  
        char *temp = new char[len*2+2];  
        int i = 1, j = 0, tmpint;  
        temp[0] = '#';  
        while(str[j]!='\0')  
        temp[i++] = str[j++],temp[i++] = '#';  
        temp[i] = '\0';  
        int mmax = 0;  
        i = len, j = len;  
        while(i>=0&&j<len*2+1)  
        {  
            if((tmpint=clac(temp,i--,len*2+1))>mmax)  
                mmax = tmpint;  
            if(mmax==2*i+3)  
                break;  
            if((tmpint=clac(temp,j++,len*2+1))>mmax)  
                mmax = tmpint;  
            if(mmax==2*i+3)  
                break;  
        }  
        return mmax/2;  
    }  
      
      
    int main()  
    {  
        int n;  
        cin>>n;  
        string str;  
        while(n--)  
        {  
            cin>>str;  
            cout<<init(str.c_str(),str.length())<<endl;;  
        }  
    }  
    

    依然超时- -囧

    相关文章

      网友评论

          本文标题:最长回文串子串 渣渣版

          本文链接:https://www.haomeiwen.com/subject/rojatxtx.html