中心拓展法求最大回文长度
import java.util.Scanner;
/**
* 中心拓展法求输入字符串最大回文长度
* 1.字符串长度为奇数时
* 2.字符串长度为偶数时
* @author hg
*
*/
public class PalindromeNumberDemo {
public static int isPalindrome(String str) {
int n = str.length();
int max = 0 ;
for(int i=0;i<n-1;i++) {
//当输入字符串长度为奇数时
for(int j=0;i-j>=0 && j+i<n;j++) {
if(str.charAt(i-j) != str.charAt(i+j))
break;
else {
max = max>(2*j+1)?max:(2*j+1);
}
}
//当输入字符串长度为偶数时
for(int j=0;i-j>=0 && i+j+1<n;j++) {
if(str.charAt(i-j) != str.charAt(i+j+1))
break;
else {
max = max>(2*j+2)?max:(2*j+2);
}
}
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.print(str + " 最大回文长度是:" + isPalindrome(str));
}
}