-
-
Save ukipoi/c58c7c41196e4c755ec0a3dbd982ab3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String longestPalindrome(String s) { | |
int max = Integer.MIN_VALUE; | |
int start = 0, end = 0; | |
for (int i = 1; i < s.length(); i++) { | |
int left, right; | |
if (s.charAt(i) == s.charAt(i - 1)) { | |
left = i - 1; | |
right = i; | |
while (left >= 0) { | |
left--; | |
right++; | |
if (left < 0 || right >= s.length() || s.charAt(left) != s.charAt(right)) { | |
if (right - left - 2 > max) { | |
max = right - left - 2; | |
start = left + 1; | |
end = right - 1; | |
} | |
break; | |
} | |
} | |
} | |
if (i + 1 < s.length()) | |
if (s.charAt(i - 1) == s.charAt(i + 1)) { | |
left = i - 1; | |
right = i + 1; | |
while (left >= 0 && right < s.length()) { | |
left--; | |
right++; | |
if (left < 0 || right >= s.length() || s.charAt(left) != s.charAt(right)) { | |
if (right - left - 2 > max) { | |
max = right - left - 2; | |
start = left + 1; | |
end = right - 1; | |
} | |
break; | |
} | |
} | |
} | |
} | |
return s.substring(start, end + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment