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
| class Solution { public String longestPalindrome(String s) { int len = s.length(); char[] ch = s.toCharArray(); int maxLength = 0; String result = "";
for (int i = 0; i < len; i++) { int maxSubLength = Math.min(i, len - 1 - i); for (int j = 0; j <= maxSubLength; j++) { if (ch[i + j] == ch[i - j]) { if (2 * j + 1 > maxLength) { maxLength = 2 * j + 1; result = s.substring(i - j, i + j + 1); } } else { break; } }
if (i + 1 < len && ch[i] == ch[i + 1]) { int j = 0; while (i - j >= 0 && i + 1 + j < len && ch[i - j] == ch[i + 1 + j]) { if (2 * (j + 1) > maxLength) { maxLength = 2 * (j + 1); result = s.substring(i - j, i + 1 + j + 1); } j++; } } }
return result; } }
|