1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class LongestPalindromeLeetcode5 { public static void main(String[] args) { System.out.println(longestPalindrome("babad")); System.out.println(longestPalindrome("cbbd")); System.out.println(longestPalindrome("a")); }
record Result(int i, int length) { static Result max(Result r1, Result r2, Result r3) { Result m = r1; if (r2.length > m.length) { m = r2; } if (r3.length > m.length) { m = r3; } return m; } }
static String longestPalindrome(String s) { char[] chars = s.toCharArray(); Result max = new Result(0, 1); for (int i = 0; i < chars.length - 1; i++) { Result r1 = extend(chars, i, i); Result r2 = extend(chars, i, i + 1); max = Result.max(max, r1, r2); } return new String(chars, max.i, max.length); }
private static Result extend(char[] chars, int i, int j) { int len = chars.length; while (i >= 0 && j < len && chars[i] == chars[j]) { i--; j++; } i++; return new Result(i, j - i); } }
|