题目描述
对于一个字符串,请设计一个高效算法,计算其中最长回文子串的长度。
给定字符串A以及它的长度n,请返回最长回文子串的长度。
例如:输入 “abc1234321ab”, 12
返回值:7
//最长回文子串
public static int getLongestPalindrome(String A, int n) {
if (A == null || A.length() <= 1) {
return 0;
}
int maxLen = 0;
byte[] array = A.getBytes();
int resultMaxLen = 0;
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > 0; j--) {
if (maxLen > j - i + 1) {
break;
}
if (array[i] == array[j]) {
int tempLen = j - i + 1;
if (maxLen > tempLen) {
break;
}
int k = 0;
boolean b = true;
while (k < tempLen / 2) {
k++;
if (array[i + k] != array[j - k]) {
b = false;
resultMaxLen = Math.max(resultMaxLen, maxLen);
maxLen = 0;
break;
}
}
if (b) {
maxLen = Math.max(maxLen, tempLen);
resultMaxLen = Math.max(resultMaxLen, maxLen);
}
}
}
}
return resultMaxLen;
}
版权声明:本文为huanongying123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。