I currently have the following implementation that handles finding the shortest palindrome with a given string by inserting the minimum number of characters, but only handling character insertions at the front to create the shortest palindrome.
But with the following implementation or if there's any better out there, how can I do so where the characters can be inserted at any point(s) in the string to make it a palindrome?
Will accept and upvote the answer. Thank you
public class Answer {
public String findShortestPalindrome(String s) {
int len = s.length();
if (len <= 1) {
return s;
}
int i = len - 1;
for (; i >= 0; --i) {
if (stringIsPalindrome(s, 0, i)) {
break;
}
}
StringBuilder sb = new StringBuilder(s.substring(i + 1));
sb.reverse().append(s);
return sb.toString();
}
public boolean stringIsPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}
DIFFERENCE Looking for shortest palindrome that handles insertion in any point in the string.