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"
.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.
题目链接:https://leetcode.com/problems/shortest-palindrome/
public class Solution {
void getNext(int[] nxt, String s, int len) {
int i = 0, j = -1;
nxt[0] = -1;
while (i < len) {
if (j == -1 || s.charAt(i) == s.charAt(j)) {
i ++;
j ++;
nxt[i] = j;
}
else {
j = nxt[j];
}
}
}
String reverse(String s) {
StringBuffer sb = new StringBuffer("");
for (int i = s.length() - 1; i >= 0; i --) {
sb.append(s.charAt(i));
}
return sb.toString();
}
public String shortestPalindrome(String s) {
int len = s.length();
if (len == 0) {
return "";
}
StringBuffer t = new StringBuffer("");
t.append(s);
t.append("@");
t.append(reverse(s));
int len2 = len * 2 + 1;
int[] nxt = new int[len2 + 1];
getNext(nxt, t.toString(), len2);
return new StringBuffer(t.substring(len + 1, len2 - nxt[len2])).append(s).toString();
}
}