您的位置:首页 > 其它

LeetCode 214. Shortest Palindrome(最短回文)

2016-05-06 02:42 363 查看
原题网址:https://leetcode.com/problems/shortest-palindrome/

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.

For example:

Given
"aacecaaa"
, return
"aaacecaaa"
.

Given
"abcd"
, return
"dcbabcd"
.
方法一:应用Manacher方法求出最长回文前缀。

public class Solution {
public String shortestPalindrome(String s) {
if (s == null) return null;
if (s.length() == 0) return "";
char[] sa = s.toCharArray();
char[] ma = new char[sa.length*2+1];
ma[0] = '#';
for(int i=0, j=1; i<sa.length; i++, j+=2) {
ma[j] = sa[i];
ma[j+1] = '#';
}
int m = ma.length/2;
int[] radius = new int[ma.length];
int rightmost = 1;
int center = 1;
int patch = sa.length - 1;
for(int i=1; i<=ma.length/2; i++) {
int min = rightmost <= i ? 1 : Math.min(rightmost-i, radius[center - (i -center)]) + 1;
for(int r=min; i-r>=0; r++) {
if (ma[i-r] != ma[i+r]) break;
radius[i] = r;
if (i-r==0) patch = sa.length - i;
}
if (rightmost < i+radius[i]) {
rightmost = i + radius[i];
center = i;
}
}
char[] palindrome = new char[sa.length + patch];
for(int j=0, k=sa.length-1; j<patch; j++, k--) palindrome[j] = sa[k];
System.arraycopy(sa, 0, palindrome, patch, sa.length);
return new String(palindrome);
}
}


方法二:应用KMP算法找出最长回文前缀。



源代码:

public class Solution {
public String shortestPalindrome(String s) {
char[] ma = new StringBuilder(s).append("#").append(new StringBuilder(s).reverse().toString()).toString().toCharArray();
int[] next = new int[ma.length];
for(int i=1; i<ma.length; i++) {
int j=next[i-1];
while (j>0 && ma[j]!=ma[i]) j=next[j-1];
next[i] = j + (ma[j]==ma[i]? 1 : 0);
}
return new StringBuilder(s.substring(next[ma.length-1])).reverse().toString()+s;
}
}


参考:http://blog.csdn.net/v_july_v/article/details/7041827/

此外还有很多其他关于KMP方法的讨论,请自行搜索。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: