nowcoder 非对称之美 (思维题)

非对称之美
题目描述

给出一个字符串,求最长非回文子字符串的长度

输入描述:

在一行中给出一个字符串 s, 1 ≤ ∣ s ∣ ≤ 1 0 7 1 \le |s| \le 10^7 1s107,

输出描述:

一个整数

示例1
输入

meow

输出

4

解题思路分析


  • 如果字符串本身不是回文串,直接输出n;
  • 如果字符串本身是回文串,那么n-1长度的字符串一定不是回文串,就相当于去掉头或者去掉尾,首尾不再对称,一定不是回文串;
  • 特判一种特殊情况,所有字母都相同的情况下,直接输出0,如aaaaaaaaa最长非回文子串的长度是0。

#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<cstring>
#include<unordered_map>
#include<numeric>
using namespace std;

string s;

bool isSame(){ //判断是否只有一种字母
    auto cur = s[0];
    for(int i = 1;i < s.size(); i++){
        if(cur != s[i]) return false;
    }
    return true;
}

int main()
{
    cin >> s;
    if(isSame()) {  //如果是"aaaaaaa"的情况,输出0
    	cout << 0 << endl;
    	return 0;
    }
    int n = s.size();
    string t = s;
    reverse(t.begin(),t.end());
    if(s != t) cout << n << endl;
    else{
        cout << n - 1 << endl;
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值