publicclassShortestPalindrome{ /** * 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. * * Example 1: * * Input: "aacecaaa" * Output: "aaacecaaa" * Example 2: * * Input: "abcd" * Output: "dcbabcd" */ publicstaticvoidmain(String[] args){ String[] test = {"hello", "aaa", "a", "de"}; for (String s: test){ // System.out.println(isPalidrome(s)); System.out.println(shortestPalindrome(s)); } } publicstatic String shortestPalindrome(String s){ if (isPalidrome(s)) return s; s = new StringBuffer(s).reverse().toString(); String ss = s; int length = 1; while(!isPalidrome(ss)){ ss = s + new StringBuffer(s.substring(0, length)).reverse().toString(); length ++; } return ss; }