Skip to content

Instantly share code, notes, and snippets.

@ebanisadr
Created November 6, 2017 06:55
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 ebanisadr/77e282a9943881fb4106d0f2c562cae2 to your computer and use it in GitHub Desktop.
Save ebanisadr/77e282a9943881fb4106d0f2c562cae2 to your computer and use it in GitHub Desktop.
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