• Manacher算法



    /**
    * Manacher算法
    * <p>
    * 又叫“马拉车”算法,可以在时间复杂度为O(n)的情况下求解一个字符串的最长回文子串长度的问题
    */
    public class Manacher {

    public static int manacher(String s) {
    if (s == null || s.length() == 0) {
    return 0;
    }
    char[] arr = manacherString(s);
    int[] result = new int[arr.length];
    int max = Integer.MIN_VALUE;
    int r = -1;
    int c = -1;
    for (int i = 0; i < arr.length; i++) {
    result[i] = r > i ? Math.min(result[2 * c - i], r - i) : 1;
    while (i - result[i] > -1 && i + result[i] < arr.length) {
    if (arr[i - result[i]] == arr[i + result[i]]) {
    result[i]++;
    } else {
    break;
    }
    }
    if (i + result[i] > r) {
    r = i + result[i];
    c = i;
    }
    max = Math.max(max, result[i]);
    }
    return max - 1;
    }

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

    public static void main(String[] args) {
    System.out.println(manacher("abc1234321cbs"));
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    线程安全的单例模式
    rsync 不真正同步,只显示更新的内容
    Python_元组、字典内建方法详解
    Python_元组、字典内建方法详解
    数组求差集
    svn数据库自动发布程序
    perl 比较目录
    被驱动表 拼接列无法走索引
    FILTER NESTLOOP 中驱动表问题
    Linux_SystemLogManager
  • 原文地址:https://www.cnblogs.com/laydown/p/13982751.html
Copyright © 2020-2023  润新知