目录
牛客_非对称之美_最长非回文字符串
题目解析
找到规律就是最长非回文字符串(判断是否全同->0,否则是n-1(回文减去1)或n)。
C++代码
#include <iostream>
using namespace std;
int main() // (判断是否全同->0,否则是n-1(回文减去1)或n)
{
string str;
cin >> str;
int sz = str.size();
bool flag = true;
for(int i = 0; i < sz; ++i)
{
if(str[i] != str[0]) // 判断是否全同
{
flag = false;
}
}
if(flag)
{
cout << 0 << endl;
return 0;
}
int left = 0, right = sz - 1;
flag = true; // 判断整个串是否是回文串
while(left < right)
{
if(str[left] != str[right])
{
flag = false;
break;
}
++left;
--right;
}
if(flag)
cout << sz - 1<< endl;
else
cout << sz << endl;
return 0;
/*
string str;
cin >> str;
int sz = str.size(), res = 1;
for(int i = 0; i < sz; ++i)
{
int left = i, right = sz - 1;
while(left < right)
{
if(str[left] != str[right])
break;
--right;
}
// cout << right - left + 1 << endl;
res = max(res, right - left + 1);
}
cout << res;
// eeeeemeeeee处理不了
return 0;
*/
}
Java代码
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
char[] s = in.next().toCharArray();
int n = s.length;
boolean flag = false;
for(int i = 1; i < n; i++)
{
if(s[i] != s[0])
{
flag = true;
break;
}
}
if(flag == true) // 不是相同的字符
{
flag = false;
// 判断本⾝是不是回⽂
int left = 0, right = n - 1;
while(left < right)
{
if(s[left] == s[right])
{
left++;
right--;
}
else
{
flag = true;
break;
}
}
if(flag == true)
System.out.println(n);
else
System.out.println(n - 1);
}
else // 是相同字符
{
System.out.println(0);
}
}
}
标签:right,Java,OJ,int,之美,flag,str,回文,left
From: https://blog.csdn.net/GRrtx/article/details/143019388