题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param A string字符串
* @return int整型
*/
public int getLongestPalindrome (String A) {
// write code here
int maxLen = 0;
for(int k = 0;k < A.length();k++) {
int i = k-1;
int j = k+1;
int curLen = 1;
char ch = A.charAt(k);
while (i > 0 && A.charAt(i) == ch) {
i--;
curLen+=1;
}
// if (k == 2) {
// System.out.println("1--cur:"+curLen+" i:"+i);
// }
while (j < A.length() && A.charAt(j) == ch) {
j++;
curLen+=1;
}
// if (k == 2) {
// System.out.println("2--cur:"+curLen+" j:"+j);
// }
//由于输入 "abbba" 后返回结果为 3,而不是 5,所以通过打印调试
//调试后得出:下面while第一个条件应该为i >=0 而不是 i>0
while (i >=0 && j < A.length() && A.charAt(i) == A.charAt(j)) {
i--;
j++;
curLen+=2;
}
// if (k == 2) {
// System.out.println("3--cur:"+curLen+" i:"+i+" j:"+j);
// }
//System.out.println("cur:"+curLen+" max:"+maxLen+" k:"+k+" ch:"+ch);
if (curLen > maxLen) {
maxLen = curLen;
}
}
return maxLen;
}
}

