manacher算法

概念:求字符串的最大回文串
1.先处理成偶数串
2.回文半径
3.回文半径最右边界,并记录最早中心位置

package basic_class_02;

public class Code_04_Manacher {

    public static char[] manacherString(String str) {
        char[] charArr = str.toCharArray();
        char[] res = new char[str.length() * 2 + 1];
        int index = 0;
        for (int i = 0; i != res.length; i++) {
            res[i] = (i & 1) == 0 ? '#' : charArr[index++];
        }
        return res;
    }

    public static int maxLcpsLength(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        char[] charArr = manacherString(str);
        int[] pArr = new int[charArr.length];
        int index = -1;
        int pR = -1;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i != charArr.length; i++) {
            pArr[i] = pR > i ? Math.min(pArr[2 * index - i], pR - i) : 1;

            while (i + pArr[i] < charArr.length && i - pArr[i] > -1) {
                if (charArr[i + pArr[i]] == charArr[i - pArr[i]])
                    pArr[i]++;
                else {
                    break;
                }
            }

            if (i + pArr[i] > pR) {
                pR = i + pArr[i];
                index = i;
            }
            
            max = Math.max(max, pArr[i]);
        }

        return max - 1;
    }

    public static void main(String[] args) {
        String str1 = "abc1234321ab";
        System.out.println(maxLcpsLength(str1));
    }

}

扩展题

给定一个字符串str1, 只能往str1的后面添加字符变成str2, 要求str2
整体都是回文串且最短。
举例:
str1 = ABC12321, 返回ABC12321CBA


你可能感兴趣的:(manacher算法)