leetcode5. 最长回文子串(Manacher - java)
发布人:shili8
发布时间:2025-03-07 04:27
阅读次数:0
**最长回文子串 (Manacher)**###介绍最长回文子串是指在一个给定的字符串中,找出最长的回文子串。回文子串是指从左到右读和从右到左读都一样的子串。
本题使用 Manacher 算法来解决这个问题。Manacher 算法是一种高效的算法,用来求解最长回文子串的问题。
###代码实现
javapublic class Solution { public String longestPalindrome(String s) { // 将字符串中的奇数长度的回文子串转换为偶数长度的回文子串 String t = manacher(s); int start =0; int maxLen =0; for (int i =0; i < t.length(); i++) { if ((i &1) ==0 && i +1 < t.length() && t.charAt(i) == t.charAt(i +1)) { start = i /2; maxLen = (t.length() - i) /2 *2; // 找到最长回文子串 while (start >=0 && start + maxLen < t.length() && t.charAt(start) == t.charAt(start + maxLen)) { start--; maxLen +=2; } return s.substring((start +1) /2 - (maxLen -1) /2, (start +1) /2); } } // 如果没有找到回文子串,则返回空字符串 return ""; } private String manacher(String s) { StringBuilder t = new StringBuilder(); for (char c : s.toCharArray()) { t.append("#").append(c).append("#"); } int n = t.length(); char[] arr = t.toString().toCharArray(); int[] p = new int[n]; int C =0, R =0; for (int i =1; i < n -1; i++) { // 如果当前位置的回文子串长度小于等于右边界,则使用旧的回文子串 p[i] = Math.min(R - i, p[2 * C - i]) if not (R - i >=0) else0; while (arr[i + p[i] +1] == arr[i - p[i] -1]) { p[i]++; } // 如果当前位置的回文子串长度大于右边界,则更新右边界 if (i + p[i] > R) { C = i; R = i + p[i]; } } StringBuilder ans = new StringBuilder(); for (int i =1; i < n -1; i++) { // 如果当前位置的回文子串长度为奇数,则将其转换为偶数长度的回文子串 if ((i &1) ==0 && i +1 < n -1 && arr[i] == arr[i +1]) { ans.append(arr[i]); } } return ans.toString(); } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.longestPalindrome("babad")); // "bab" System.out.println(solution.longestPalindrome("cbbd")); // "bb" } }
### 解释本题使用 Manacher 算法来求解最长回文子串的问题。Manacher 算法是一种高效的算法,用来求解最长回文子串的问题。
首先,我们将字符串中的奇数长度的回文子串转换为偶数长度的回文子串,然后使用 Manacher 算法来找到最长回文子串。
Manacher 算法是一种高效的算法,用来求解最长回文子串的问题。它首先将字符串中的奇数长度的回文子串转换为偶数长度的回文子串,然后使用一个数组 `p` 来存储每个位置的回文子串长度。
最后,我们找到最长回文子串并返回其值。
### 示例示例1:
* 输入:"babad"
* 输出:"bab"
示例2:
* 输入:"cbbd"
* 输出:"bb"
示例3:
* 输入:"a"
* 输出:"a"
示例4:
* 输入:""
* 输出:""
### 复杂度时间复杂度:O(n),其中 n 是字符串的长度。
空间复杂度:O(n)。