☀L2-008 最长对称子串 (25分)[PTA][暴力]

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

非马拉车来解最长对称子串,比较暴力的方式,在看的时候还看到了用dp的方式

int max=1;//★★★★★非空字符串,最短对称子串的长度为1,否则样例会有一个不过

---------------------

如果子串偶对称

for(int i=0;i<len;i++)

    {

        int x=i,y=i+1;

        int ans=0;

        while(s[x]==s[y]&&x>=0&&y<len)

        {

            x--;

            y++;

            ans+=2;

        }

        if(ans>max)

        {

            max=ans;

        }

    }

---------------------

如果子串奇对称

for(int i=1;i<len;i++)

    {

        int x=i-1,y=i+1;

        int ans=1;//答案先加上中间的那个字符

        while(s[x]==s[y]&&x>=0&&y<len)

        {

            x--;

            y++;

            ans+=2;

        }

        if(ans>max)

        {

            max=ans;

        }

    }

ac代码:

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f;

int main()
{
    string s;
    getline(cin,s);
    int len=s.size();
    int max=1;
    for(int i=0;i<len;i++)
    {
        int x=i,y=i+1;
        int ans=0;
        while(s[x]==s[y]&&x>=0&&y<len)
        {
            x--;
            y++;
            ans+=2;
        }
        if(ans>max)
        {
            max=ans;
        }
    }
    for(int i=1;i<len;i++)
    {
        int x=i-1,y=i+1;
        int ans=1;
        while(s[x]==s[y]&&x>=0&&y<len)
        {
            x--;
            y++;
            ans+=2;
        }
        if(ans>max)
        {
            max=ans;
        }
    }
    cout<<max;
    return 0;
}

参考:https://blog.csdn.net/qq_34115899/article/details/79680882?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160629601719195283012726%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=160629601719195283012726&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v1~rank_blog_v1-26-79680882.pc_v1_rank_blog_v1&utm_term=L2-008+最长对称子串++25分&spm=1018.2118.3001.4450 

马拉车算法

#include <iostream>
#include <cstdio>
#include <cstring>
#define MAX 1000
using namespace std;

char s[MAX + 1];
char t[MAX * 2 + 5] = {'@','#'};
int p[MAX * 2 + 5];
int Manacher(char *str) {
    int len = strlen(str);
    for(int i = 1;i <= len;i ++) {
        t[i * 2] = str[i - 1];
        t[i * 2 + 1] = '#';
    }
    t[len * 2 + 2] = 0;
    int mi = 0,rpoint = 0,mr = 0;
    for(int i = 1;t[i];i ++) {
        p[i] = i < rpoint ? min(rpoint - i,p[mi * 2 - i]) : 1;
        while(t[i + p[i]] == t[i - p[i]]) p[i] ++;
        if(i + p[i] > rpoint) {
            mi = i;
            rpoint = i + p[i];
        }
        if(mr < p[i]) mr = p[i];
    }
    return mr - 1;
}
int main() {
    int i = 0;
    while((s[i] = getchar()) != '\n') i ++;
    s[i] = 0;
    printf("%d",Manacher(s));
}

猜你喜欢

转载自blog.csdn.net/qq_43660826/article/details/110150945