Given a string S, you are 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.
public String shortestPalindrome(String s){ int maxLen = 0; for(int i = 0; i < s.length(); ++i) { int len = scanMaxLen(s, i, i); if(maxLen < len) maxLen = len; len = scanMaxLen(s, i, i + 1); if(maxLen < len) maxLen = len; } StringBuilder add = new StringBuilder(s.substring(maxLen, s.length())); add.reverse(); return add.append(s).toString(); }
privateintscanMaxLen(String s, int l, int r){ int i = l, j = r; while(i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) { --i; ++j; } if(i >= 0) return0; return l == r ? (l - i) + (j - r) - 1 : (l - i) + (j - r); }