You are given a string s. You can convert s to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Input: s = "aacecaaa"
Output: "aaacecaaa"
Input: s = "abcd"
Output: "dcbabcd"
s consists of lowercase English letters only.The problem asks us to create the shortest palindrome by adding characters to the front of a string. A simple brute force way to create a palindrome is to repeatedly check each prefix of the string and find out if it forms a palindrome extending towards the rest of the string. If not, we keep adding the minimum necessary characters at the front, checking each time if the result is a palindrome.
s to get rev_s.s itself is a palindrome, return it.i of the string s:rev_s.substring(0, i) appended to the front of the original s.s.substring(i) is the largest palindromic prefix.To reduce the time complexity, we can use the Knuth-Morris-Pratt algorithm (KMP) prefix function. The idea is to find the greatest palindrome prefix in the string using the prefix and suffix match pattern from the reversed string. This helps us quickly determine which part of the string needs to be mirrored from the end.
s with # and its reversed version rev_s to create a new string concat.# is a delimiter ensuring we don't accidentally match across s and rev_s.s form a valid palindrome.s can be added in reverse at the beginning to form the shortest palindrome.