描述 | |
---|---|
知识点 | 字符串 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入一串字符 |
输出 | 输出有效长度 |
样例输入 | ABBA |
样例输出 | 4 |
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
String str = cin.nextLine();
int len=MaxLength(str);
System.out.println(len);
cin.close();
}
private static int MaxLength(String str) {
// TODO Auto-generated method stub
if(str==null||str.length()==0)
{
return -1;
}
int symLen=1;
char[] letter=str.toCharArray();
int strLen=str.length();
int curIndex=1;
while(curIndex>0&&curIndex<strLen-1)
{
//odd symmetrical length,the 'pivot' char is letter[curIndex]
int i=curIndex-1;
int j=curIndex+1;
while(i>=0&&j<=(strLen-1)&&letter[i]==letter[j])
{
i--;
j++;
}
int newLen=j-i-1;
if(newLen>symLen)
{
symLen=newLen;
}
//even symmetrical length,the 'pivot' chars are letter[curIndex] and letter[curIndex+1]
i=curIndex;
j=curIndex+1;
while(i>=0&&j<=(strLen-1)&&letter[i]==letter[j])
{
i--;
j++;
}
newLen=j-i-1;
if(newLen>symLen)
{
symLen=newLen;
}
curIndex++;
}
return symLen;
}
}