package org.example.test; /** * 暴力算法,后续优化 */ public class LongestPalindromeTest { public static void main(String[] args) { System.out.println(getLongestPalindrome("baab", 4)); } public static int getLongestPalindrome(String A, int n) { int ret = 0; for (int i = 0; i < A.length(); i++) { for (int j = 0; j < A.length(); j++) { boolean p = isPalindrome(A, i, j); if (p) { ret = Math.max(ret, j - i + 1); } } } return ret; } private static boolean isPalindrome(String a, int i, int n) { int t = n - i + 1; while (a.charAt(i) == a.charAt(n)) { i++; n--; if (i >= n) { break; } } if (t % 2 == 0) { return i - 1 == n; } else { return i == n; } } }