Is there a better way to do it? The findMaxPalindrome needs to be called
twice.
String maxPalindrome(String str) {
String maxPalindrome = "";
for(int i=0; i// when the palindrome is odd number, i.e. "aabaa"
maxPalindrome = findMaxPalindrome(str,i,i,maxPalindrome);
// when the palindrom is even number, i.e. "cccc"
maxPalindrome = findMaxPalindrome(str,i,i+1,maxPalindrome);
}
return maxPalindrome;
}
String findMaxPalindrome(String str, int low, int high, String maxPalindrome
) {
while(low>=0 && highhigh)) {
low--;
high++;
}
String palindrome = str.substring(low+1,high);
if(palindrome.length()>maxPalindrome.length()){
maxPalindrome = palindrome;
}
return maxPalindrome;
}
Testing cases:
System.out.println(maxPalindrome("abcdeed"));
System.out.println(maxPalindrome("abccbac"));
System.out.println(maxPalindrome("dabafe"));
System.out.println(maxPalindrome("racecar"));
System.out.println(maxPalindrome("cabacd"));
System.out.println(maxPalindrome("dcabac"));
System.out.println(maxPalindrome("ddecccce"));
deed
abccba
aba
racecar
cabac
cabac
ecccce