Skip to content

Instantly share code, notes, and snippets.

@ukipoi
Created January 8, 2021 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ukipoi/c58c7c41196e4c755ec0a3dbd982ab3a to your computer and use it in GitHub Desktop.
Save ukipoi/c58c7c41196e4c755ec0a3dbd982ab3a to your computer and use it in GitHub Desktop.
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