【问题描述】[中等]
【解答思路】
1. 字符串哈希
复杂度
class Solution {public String shortestPalindrome(String s) {int n = s.length();int base = 131, mod = 1000000007;int left = 0, right = 0, mul = 1;int best = -1;for (int i = 0; i < n; ++i) {left = (int) (((long) left * base + s.charAt(i)) % mod);right = (int) ((right + (long) mul * s.charAt(i)) % mod);if (left == right) {best = i;}//倒叙进制mul = (int) ((long) mul * base % mod);}String add = (best == n - 1 ? "" : s.substring(best + 1));StringBuffer ans = new StringBuffer(add).reverse();ans.append(s);return ans.toString();}
}
2. KMP
复杂度
class Solution {public String shortestPalindrome(String s) {int n = s.length();int[] fail = new int[n];Arrays.fill(fail, -1);//next数组for (int i = 1; i < n; ++i) {int j = fail[i - 1];while (j != -1 && s.charAt(j + 1) != s.charAt(i)) {j = fail[j];}if (s.charAt(j + 1) == s.charAt(i)) {fail[i] = j + 1;}}int best = -1;for (int i = n - 1; i >= 0; --i) {while (best != -1 && s.charAt(best + 1) != s.charAt(i)) {best = fail[best];}if (s.charAt(best + 1) == s.charAt(i)) {++best;}}String add = (best == n - 1 ? "" : s.substring(best + 1));StringBuffer ans = new StringBuffer(add).reverse();ans.append(s);return ans.toString();}
}作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/shortest-palindrome/solution/zui-duan-hui-wen-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
【总结】
1. 【数据结构与算法】字符串匹配 BF算法 RK算法
2.【数据结构与算法】字符串匹配 KMP 算法
3.RK算法 本质是hash KMP算法关键求next数组
转载链接:https://leetcode-cn.com/problems/shortest-palindrome/solution/zui-duan-hui-wen-chuan-by-leetcode-solution/