非对称之美
题目描述
给出一个字符串,求最长非回文子字符串的长度
输入描述:
在一行中给出一个字符串 s, 1 ≤ ∣ s ∣ ≤ 1 0 7 1 \le |s| \le 10^7 1≤∣s∣≤107,
输出描述:
一个整数
示例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;
}