/* * 214. Shortest Palindrome * 2016-6-11 by Mingyang * My solution took n^2 time and exceeding the time limits * 大概思路就是从第一个点开始找到最后一个不能成为palindrome的点,其余的都reverse加到前面去 * 我跟标准答案的唯一区别!就是我的mark其实就是标准答案里面的j */
public String shortestPalindrome(String s) { int i=0; int j=s.length()-1; while(j>=0){ if(s.charAt(i)==s.charAt(j)){ i++; } j--; } if(i==s.length()) return s; String suffix = s.substring(i); String prefix = new StringBuilder(suffix).reverse().toString(); String mid = shortestPalindrome(s.substring(0, i)); return prefix+mid+suffix; }