Manacher算法
求回文子串 O(n) manacher 算法
注:此处引用他人的文章
题目:
解答:
public class LongestPalindromicSubstring { public String longestPalindrome(String s) { StringBuilder sb = new StringBuilder(s); int[] p = new int[2*s.length()+3]; //p数组用来保存每个字符的回文半径 sb.insert(0, '?'); //这里在开头和结尾设置两个不同的字符,是为了向两边扫描的时候设置字符对比结束,sb最终结果为(?#...#!) for(int i=0;i<=s.length();i++){ sb.insert(2*i+1, '#'); } sb.insert(2*s.length()+2, '!'); int maxL=0,maxId=0,id=0; //maxL是最长的半径 int i; for(i=1;i<p.length-1;i++){ if(maxId > i){ p[i] = min(p[2*id-i], maxId-i); }else{ p[i] = 1; } while(sb.charAt(i+p[i]) == sb.charAt(i-p[i])){ p[i]++; } /*if(p[i] + i > maxId){ maxId = p[i]+i; id = i; }*/ if(p[i] > maxL){ maxL = p[i]; id = i; maxId = p[i]+i; } } int index = 2*id - maxId + 1; index = (index+1)/2-1; return s.substring(index, p[id]-1+index); } private int min(int a, int b){ return a<b?a:b; } public static void main(String[] args) { String s = "ababcbaba"; String palindrome = new LongestPalindromicSubstring().longestPalindrome(s); System.out.println(palindrome); } }