Leetcode 214: Shortest Palindrome, leetcodepalindrome
Shortest PalindromeTotal Accepted:
172Total Submissions:
1344
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 using Ming this transformation.
For example:
Given"aacecaaa"
, Return"aaacecaaa"
.
Given"abcd"
, Return"dcbabcd"
.
[Idea]
Expand from a char to both sides (the characters on both sides are equal). If the string header can be extended all the time, add the remaining reverse at the end to the header of the original string.
Tips: 1. The Central Axis character starts from the middle, so that it is found to be the shortest. 2. The Central Axis character may be one or two.
[CODE]
public class Solution { public String shortestPalindrome(String s) { if(s.length()<=1 ) return s; int center = (s.length()-1)/2; String res=""; for(int i=center; i>=0; i--) { if(s.charAt(i) == s.charAt(i+1)) { if( (res = check1(s, i, i+1)) !=null) return res; } if( (res = check1(s, i, i)) !=null) return res; } return res; } //aabaac private String check1(String s, int l, int r) { int i=1; for(; l-i>=0; i++) { if(s.charAt(l-i) != s.charAt(r+i) ) break; } if(l-i>=0) return null; StringBuilder sb = new StringBuilder(s.substring(r+i)); sb.reverse(); return sb+s; }}