Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find longest Palindrome Substring
public class PalindromeSubstring {
public static String getLongestPalindrome(String s1) {
if (s1.length() == 0)
return "";
int palindromeStart = -1;
int palindromeEnd = -2;
for (int i = 0; i < s1.length(); i++) {
for (int type = 0; type <= 1; type++) {
int start;
int end;
if (type == 0) {
//check odd palindromes
start = i;
end = i;
} else
//check even palindromes
if (i < s1.length() - 1) {
start = i+1;
end = i;
} else
break;
while ((start - 1 >= 0) && (end + 1 < s1.length())) {
if (s1.charAt(start - 1) == s1.charAt(end + 1)) {
start--;
end++;
} else
break;
}
if (end - start > palindromeEnd - palindromeStart) {
palindromeStart = start;
palindromeEnd = end;
}
}
}
return s1.substring(palindromeStart, palindromeEnd+1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.