Longest Palindromic Substring-----LeetCode进阶路⑤
- 题目描述
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
给定一个字符串s,找出s中最长的回文子字符串。可假设s的最大长度是1000。
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
- 思路分析
对于回文串,大家一定都不陌生啦,即正读,反读都一样的字符串。
求解最长回文子串问题,必须是马大神的Manacher's Algorithm,时间复杂度O(n),线性搞定,完虐中心扩展和动态规划这些思路
Manacher's Algorithm思路如下:
- 对给定字符串进行预处理:
①字符两两之间和字符串头尾都插入任一特殊字符,确保处理后的字符串长度一定为奇数,不必再分情况列出奇偶两种情况。eg:abba (4)—>$a$b$b$a$(9) cde(3)—>$c$d$e$(7)
②在处理后的字符串前后各加一个相异的特殊字符,防止字符越界问题 - 开一个数组c来存储以B中的第n个元素为中心的最大回文子串,即B[n]为中心的最大回文子串(为了方便起见,原始字符串称A,处理后的字符串称B,新数组称为c)
eg:B $ a $ b $ b $ a $
c 0 1 0 1 4 1 0 1 0
从eg中,我们可以发现c[n] 即以A[n]为中心的最长回文子串长度
所以找到回文子串的最大长度等价于:找到最大的c[n] - 增加两个帮手,pos来表示最大回文子串的中心,max(=pos+c[pos])表示最大回文子串的半径。
- 下面进入大餐,充分利用回文串 内回文 的对称性,这里我怕说不好,贴一下大神的助攻下
https://blog.crimx.com/2017/07/06/manachers-algorithm/
https://articles.leetcode.com/longest-palindromic-substring-part-ii/
- 源码附录
class Solution {
public String longestPalindrome(String s) {
if(s.length()<=1){
return s;
}
StringBuilder sb = new StringBuilder();
sb.append("#");
for(int i=0;i<s.length();i++){
sb.append("$");
sb.append(s.charAt(i));
}
sb.append("$*");
int pos = 0;
int r = 0;
int mi = 0;
int ms = 0;
int[] t = new int[sb.length()];
for(int i=1;i<sb.length();i++){
int mirrorCur = 2*pos-i;
t[i] = (i>r) ? 1:(Math.min(t[mirrorCur],r-i));
while((i+t[i])<sb.length() && (sb.charAt(i+t[i]) == sb.charAt(i-t[i]))){
t[i] ++;
}
if(i+t[i] > r){
r = t[i] + i;
pos = i;
}
if(t[i]>ms){
ms = t[i];
mi = i;
}
}
return s.substring((mi-ms)/2,(mi+ms)/2-1);
}
}
自行理解,实在不理解的话,参照下文详解版
class Solution {
public String longestPalindrome(String s) {
if(s.length()<=1){
return s;
}
StringBuilder sb = new StringBuilder();//进行预处理
sb.append("#");
for(int i=0;i<s.length();i++){
sb.append("$");
sb.append(s.charAt(i));
}
sb.append("$*");
int pos = 0;//当前情况下能够到达的最远的回文子串中心
int r = 0;//当前情况下能到达的最远回文子串半径
int mi = 0;//记录最长的回文子串中心
int ms = 0;//记录最长的回文子串半径
int[] t = new int[sb.length()];
for(int i=1;i<sb.length();i++){
int mirrorCur = 2*pos-i;//记录当前下标和pos的对称点
/*
if(i<r){//当前下标小于当前能够到达的最远回文子串的半径时,用下标的t值
t[i] = Math.min(t[mirrorCur],r-i)
}
else{//负责置1等待
t[i] = 1;
}
*/
t[i] = (i>r) ? 1:(Math.min(t[mirrorCur],r-i));
//检查并更新以当前下标为中心的回文子串到达的最远长度
while((i+t[i])<sb.length() && (sb.charAt(i+t[i]) == sb.charAt(i-t[i]))){
t[i] ++;
}
if(i+t[i] > r){ //检查并更新当前能够到达的最远的回文子串的信息
r = t[i] + i;
pos = i;
}
if(t[i]>ms){ //更新当前已知的最长的回文串子信息
ms = t[i];
mi = i;
}
}
return s.substring((mi-ms)/2,(mi+ms)/2-1);//去掉辅助符号 进行输出
}
}