Given A string S, you is allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa"
, return "aaacecaaa"
.
Given "abcd"
, return "dcbabcd"
.
Problem Solving Ideas:
The simplest way of thinking is to judge whether the substring is a palindrome string from the back to the front, and then to get the back of the former can be, but this can only grazing through the test, the most efficient of course is the KMP algorithm,
KMP can refer to Java for Leetcode 028 Implement strStr ()
Java implementation is as follows;
Public String Shortestpalindrome (string s) {for (int i=s.length (); i>=1;i--) if (Ispalindrome (s.substring ( 0, I)) return new StringBuilder (s.substring (i)). reverse () +s; Return ""; } Static Boolean ispalindrome (String s) { int left=0,right=s.length ()-1; while (left<right) if (S.charat (left++)!=s.charat (right--)) return false; return true; }
Java for Leetcode 214 shortest palindrome