【马拉车算法/动态规划】最长回文字串

最长回文字串

  • 1.问题描述
  • 2.中心扩展法(O(N^2))
  • 3.动态规划
  • 4.Manacher(马拉车算法)

1.问题描述

问题描述
常用有3种算法:中心扩展法、动态规划和Manacher算法

2.中心扩展法(O(N^2))

解释:
从中心向外扩展。
分为两种情况:第一种当回文串长度为奇数的情况;第二种当回文串长度为偶数的情况。
左右同时向外扩展,当左右不相同时停止扩展,记录最长回文串长度及起始位置。文章来源地址https://uudwc.com/A/odJn0

    public String longestPalindrome(String str) {
        if (Objects.isNull(str) || str.isEmpty()) {
            return "";
        }
        int maxStart = 0;
        int maxLength = 1;
        for (int i = 0; i < str.length(); i++) {
            for (int k = 0; k < 2; ++k) {
                int leftIndex = i - k; // k = 0表示偶数长度,k = 1表示奇数长度
                int rightIndex = i + 1;
                while (leftIndex >= 0
                        && rightIndex < str.length()
                        && str.charAt(leftIndex) == str.charAt(rightIndex)) {
                    leftIndex--;
                    rightIndex++;
                }
                if (maxLength < rightIndex - leftIndex - 1) { // 当前length = (rightIndex - 1) - (leftIndex + 1) + 1
                    maxLength = rightIndex - leftIndex - 1;
                    maxStart = leftIndex + 1;
                }
            }
        }

        return str.substring(maxStart, maxStart + maxLength);
    }     

3.动态规划

4.Manacher(马拉车算法)

原文地址:https://blog.csdn.net/Allenlzcoder/article/details/132528484

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年08月28日 16:55
爬虫(bilibili热门课程记录)
下一篇 2023年08月28日 16:55