leetcode Longest Palindromic Substring

题目链接

manacher算法

public class Solution {
    public String longestPalindrome(String s) {
            StringBuilder sb=new StringBuilder(2*s.length()+1);
            sb.append("#");
            for(int i=0;i<s.length();i++)
            {
                sb.append(s.charAt(i));
                sb.append("#");
            }

            String array=sb.toString();
            int n=array.length();

            int pi[]=new int [n];
            for(int i=0;i<n;i++)
            {
                pi[i]=0;
            }


            int max=-1;
            int index=-1;
            for(int i=0;i<n;i++)
            {
                int templ=1;
                if(i<index)
                {
                    templ=Integer.min(pi[2*index-i], max-i);
                }

                while(i-templ>=0&&i+templ<n&&array.charAt(i-templ)==array.charAt(i+templ))
                {
                    templ++;
                }
                templ--;
                pi[i]=templ;
                if(i+templ>index+max)
                {
                    max=templ;
                    index=i;
                }

            }
            int maxlength=0;
            int maxIndex=0;
            for(int i=0;i<n;i++)
            {
                if(maxlength<pi[i])
                {
                    maxlength=pi[i];
                    maxIndex=i;
                }
            }
            String aa=array.substring(maxIndex-maxlength, maxIndex+maxlength);
            StringBuilder result= new StringBuilder(aa.length());
            for(int i=0;i<aa.length();i++)
            {
                if(aa.charAt(i)=='#')
                {

                }
                else
                {
                    result.append(aa.charAt(i));
                }
            }

            return result.toString();
    }
}

你可能感兴趣的:(leetcode Longest Palindromic Substring)