(leetcode)5.最大回文子字符串 Longest Palindromic Substring--Java

来源:互联网 发布:爱淘宝天猫购物券 编辑:程序博客网 时间:2024/06/05 11:47

翻译

给定一个字符串S,找出它的最大回文子字符串。你可以假定S的最大长度为1000,并且这里存在唯一一个最大回文子字符串。
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

原文

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.



public class Solution {



    public String longestPalindrome(String s) {

        int max = 0;
        int c = 0;
        String ss = s;
        s = preProcess(s);
        int len = s.length();
        int p[] = new int[len];
        int Center = 0, Right = 0; 
        for(int i=0;i<len;i++){


             int i_mirror = 2*Center-i;
             p[i] = (Right > i) ? Math.min(Right-i, p[i_mirror]) : 0;

             if(i-p[i]<0||i+p[i]>=len) continue;
            while(s.charAt(i+p[i])==s.charAt(i-p[i])){
    //            System.out.println(i + ": ++");
                p[i]++;
                if(i-p[i]<0||i+p[i]>=len) break;
            }
            if(max<p[i]){
                max =p[i];
                c=i;
            }

              if (i + p[i] > Right) { 
                  Center = i; 
                  Right = i + p[i]; 
                } 


        }



        int t =(max-1)/2;
        int z = c/2;

  //      System.out.println(t +"   " +z);

    if((max-1)%2==0){

  return ss.substring(z-t,t+z);
    }else{

        return ss.substring(z-t,t+z+1);
    }
    }

    String preProcess(String s) { 
          int n = s.length(); 

          String ret = ""; 
          for (int i = 0; i < n; i++) 
            ret += "#" + s.charAt(i); 
           ret +="#";

          return ret; 
        }

}


有一个Manacher的算法,主要作用是不让p[i]从零开始计数,从而缩小计算范围

http://blog.csdn.net/hopeztm/article/details/7932245
0 0
原创粉丝点击