Created
November 6, 2017 06:55
-
-
Save ebanisadr/77e282a9943881fb4106d0f2c562cae2 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 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