题解 | #最长回文子串#
最长回文子串
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 // 解题思路: // 1.如果字符串为null或者空字符,则返回0 // 2.以每个元素为中心, // 3.奇数回文子串 则判断 start=i,end=i,偶数回文子串则判断 start=i,end=i+1 // 如果相等则左边减1右边加1,继续判断2边元素是否相等 if (A == null || A.equals("")) { return 0; } int max = 1; for (int i = 0; i < A.length() - 1; i++) { max = Math.max(max, Math.max(maxLength(A, i, i), maxLength(A, i, i + 1))); } return max; } private int maxLength(String a, int start, int end) { while (start >= 0 && end < a.length() && a.charAt(start) == a.charAt(end)) { start--; end++; } return end - start - 1; } }