7-8 最长对称子串 (25分) (暴力)C++

在这里插入图片描述
思路:
枚举以i为对称轴的最长对称字符串,分为奇数串和偶数串两种情况。

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <string>

using namespace std;

string s; 

int main() {
    //freopen("test.in","r",stdin);
    //freopen("test.out","w",stdout);
    
    int maxn = -1;
    int count_ = 0;
    int i;
    int l,r;
    int len;
    
    getline(cin,s);
    len = s.length();
        
    for(i = 0;i<len;i++)
    {
        //奇数串
        l = i - 1;
        r = i + 1;
        count_ = 1;
        while(l>=0&&r<len&&s[l--]==s[r++])
        {
            count_ += 2;
        } 
        maxn = max(maxn,count_);
        
        //偶数串
        l = i;
        r = i + 1;
        count_ = 0;
        while(l>=0&&r<len&&s[l--]==s[r++])
        {
            count_ += 2;
        }
        maxn = max(maxn,count_);
    }
    cout<<maxn;
    return 0; }

猜你喜欢

转载自blog.csdn.net/qq_39592312/article/details/104180300