码迷,mamicode.com
首页 > 其他好文 > 详细

5. Longest Palindromic Substring

时间:2016-05-10 12:23:43      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        String t = preprocessing(s);
        int C = 0, R = 0, i, i_mirror;
        int[] p = new int[t.length()];
        int maxLen = 0, maxC = 0, start;
        
        //Started from the first letter at the right of C, so it‘s i = 1
        for(i = 1; i < t.length()-2; i++){
            i_mirror = 2*C-i;
            if(i > R) p[i] = 0; //avoid overflow of i_mirror
            else if(p[i_mirror] <= R-i) p[i] = p[i_mirror];
            else p[i] = R-i;
            
            //Try to enlarge p[i]
            while(t.charAt(i+p[i]+1) == t.charAt(i-p[i]-1)){ //Thanks to sentinel"^""$", no need to worry about overflow
                p[i]++; //should also calculate #, which is for the letter before #
            }
            
            //update R and C
            if(i+p[i] > R){
                R = i + p[i];
                C = i;
            }
        }
        
        //find the longest parlindrome
        for(i = 1; i < t.length()-2; i++){
            if(maxLen < p[i]){
                maxLen = p[i];
                maxC = i;
            } 
        }
        start = (maxC-maxLen) >> 1;
        return s.substring(start, start+maxLen);
    }
    
    public String preprocessing(String s){
        if(s.length()==0) return "^$";
        
        String t = "^";
        for(int i = 0; i < s.length(); i++){
            t = t + "#" + s.charAt(i); //so that all the parlindrome is odd (have a Center)
        }
        t += "#$";
        return t;
    }
}

 

5. Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/5477085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!