Last active
August 29, 2015 14:15
-
-
Save dmnugent80/49388c8befed69f60281 to your computer and use it in GitHub Desktop.
Longest Palindrome
This file contains hidden or 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 void main(String[] args) | |
{ | |
String str = longestPalindrome("bananaaabjklaskdjfaldsfhalksjf"); | |
System.out.println("Longest Anagram: " + str); | |
} | |
public static String longestPalindrome(String s) { | |
int n = s.length(); | |
if (n == 0) return ""; | |
String longest = s.substring(0, 1); // a single char itself is a palindrome | |
for (int i = 0; i < n - 1; i++) { | |
String p1 = expandAroundCenter(s, i, i); | |
if (p1.length() > longest.length()) | |
longest = p1; | |
String p2 = expandAroundCenter(s, i, i+1); | |
if (p2.length() > longest.length()) | |
longest = p2; | |
} | |
return longest; | |
} | |
public static String expandAroundCenter(String s, int c1, int c2) { | |
int l = c1, r = c2; | |
int n = s.length(); | |
while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { | |
l--; | |
r++; | |
} | |
return s.substring(l + 1 , r ); | |
} | |
} | |
/*output: | |
Longest Anagram: anana | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment