import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
public int getLongestPalindrome(String A) {
// write code here
if (A == null || A.length() == 0) {
return 0;
}
if (A.length() == 1) {
return 1;
}
int res = 1;
for (int i = 0; i < A.length(); i++) {
res = Math.max(res, Math.max(helper(A, i, i), helper(A, i, i + 1)));
}
return res;
}
public int helper(String str, int left, int right) {
boolean flag = left == right ? true : false;
int counter = 0;
while (left <= right && left >= 0 && right <= str.length() - 1 &&
str.charAt(left) == str.charAt(right)) {
counter++;
left--;
right++;
}
return flag != true ? counter * 2 : counter * 2 - 1;
}
}
使用 counter 计数来求字符数比较好理解一些

京公网安备 11010502036488号