Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class LongestPalindrome {
public static String getLongestPalindrome(final String input) {
int rightIndex = 0, leftIndex = 0;
String currentPalindrome = "", longestPalindrome = "";
for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
leftIndex = centerIndex - 1; rightIndex = centerIndex + 1;
while (leftIndex >= 0 && rightIndex < input.length()) {
if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
break;
}
currentPalindrome = input.substring(leftIndex, rightIndex + 1);
longestPalindrome = currentPalindrome.length() > longestPalindrome.length() ? currentPalindrome : longestPalindrome;
leftIndex--; rightIndex++;
}
}
return longestPalindrome;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a string");
String str = s.nextLine();
String longestPali = getLongestPalindrome(str);
s.close();
System.out.println("Longest Palindrome: " + longestPali);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment