思路: 将原始字符串逆序,然后比较对应的子串即可判断是否是回文串 从开头开始的最长回文串也就找到了, 接下来只需要使用之前的方法。
将末尾不是回文串的部分倒置加到原字符串开头即可。
//给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。
//
//
//
// 示例 1:
//
//
//输入:s = "aacecaaa"
//输出:"aaacecaaa"
//
//
// 示例 2:
//
//
//输入:s = "abcd"
//输出:"dcbabcd"
//
//
//
//
// 提示:
//
//
// 0 <= s.length <= 5 * 104
// s 仅由小写英文字母组成
//
// Related Topics 字符串 字符串匹配 哈希函数 滚动哈希
// 👍 358 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String shortestPalindrome(String s) {
String string = new StringBuilder(s).reverse().toString();
int n= s.length();
int i=0;
for (; i < n; i++) {
if (s.substring(0,n-i).equals(string.substring(i))) {
break;
}
}
return new StringBuilder(s.substring(n-i)).reverse() +s;
}
}
//leetcode submit region end(Prohibit modification and deletion)