214. 最短回文串

给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。找到并返回可以用这种方式转换的最短回文串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Rabin-Karp

class Solution {

    private final int base = 131;

    private final int mod = 1000000007;

    public String shortestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }

        long left = 0, right = 0, rBase = 1;

        int bestIndex = -1;

        for (int i = 0; i < s.length(); ++i) {
            left = (left * base + s.charAt(i)) % mod;
            right = (right + rBase * s.charAt(i)) % mod;

            if (left == right) {
                bestIndex = i;
            }

            rBase = (rBase * base) % mod;
        }

        if (bestIndex == s.length() - 1) {
            return s;
        }

        String add = new StringBuilder(s.substring(bestIndex + 1)).reverse().toString();

        return add + s;

    }
}

KMP

import java.util.Scanner;

class Solution {

    private int[] getNext(String str) {
        int[] next = new int[str.length()];
        next[0] = -1;
        int i = 0, j = -1;
        while (i < str.length() - 1) {
            if (j == -1 || str.charAt(i) == str.charAt(j)) {
                if (str.charAt(++i) == str.charAt(++j)) {
                    next[i] = next[j];
                } else {
                    next[i] = j;
                }
            } else {
                j = next[j];
            }
        }
        return next;
    }

    public String shortestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }

        int[] next = getNext(s);

        int i = s.length() - 1, j = 0;

        while (i >= 0 && j < s.length()) {
            if (j == -1 || s.charAt(i) == s.charAt(j)) {
                i--;
                j++;
            } else {
                j = next[j];
            }
        }

        String add = s.substring(j);

        return new StringBuilder(add).reverse().append(s).toString();
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().shortestPalindrome(in.next()));
        }
    }
}

Manacher

posted @ 2021-12-16 16:35  Tianyiya  阅读(54)  评论(0)    收藏  举报