# 214-最短回文

Description

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".

j = length - 1,i = 0,通过j从右往左遍历字符串。若s.charAt(i) == s.charAt(j),那么i++.

s = “aacecaaa”,i = 0, j = 7

s进行分解，由于[i, length - 1]一定不是回文，那么我们必须得将这部分字符串逆序添加到头部，

https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/

class Solution {
public String shortestPalindrome(String s) {
int i = 0, n = s.length();

for(int j = n - 1;j >= 0;j--){
if(s.charAt(i) == s.charAt(j))  i++;
}
//若i == n那么s为回文，直接返回
if(i == n) return s;

String remain = new StringBuilder(s.substring(i, n)).reverse().toString();

//remain一定不是回文，直接加上，注意尾部也要添加s的尾部
//最长前缀回文一定在s.substring(0, i)中(注意是在，而不是就是s.substring(0, i))
return remain + shortestPalindrome(s.substring(0, i)) + s.substring(i, n);
}
}

class Solution {
public String shortestPalindrome(String s) {
int n = s.length();
String rev = new StringBuilder(s).reverse().toString();
String s_new = s + "#" + rev;
int n_new = s_new.length();
int[] lps = new int[n_new];

for(int i = 1;i < n_new;i++){
int t = lps[i - 1];
while(t > 0 && s_new.charAt(i) != s_new.charAt(t))  t = lps[t - 1];
if(s_new.charAt(i) == s_new.charAt(t))  ++t;
lps[i] = t;
}
//由于lps[n_new - 1]为最长前缀回文串的长度，那么将其减去得到不是回文串的长度
//即rev.substring(0, n - lps[n_new - 1])为非回文串，将其添加在前端即可
return rev.substring(0, n - lps[n_new - 1]) + s;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120