5. Longest Palindromic Substring

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.

 Solution I: 动态规划。dp[j][i]取决于dp[j+1][i-1]

public class Solution {
    public String longestPalindrome(String s) {
        if(s.length()==0) return s;
        int maxLen = 1;
        int start = 0;
        boolean[][] dp = new boolean[s.length()][s.length()];
        int i,j;
        for(i = 0; i < s.length(); i++){ //initial state
            dp[i][i] = true;
            for(j = i+1; j < s.length(); j++){
                dp[i][j] = false;
            }
        }
        
        for(i = 1; i < s.length(); i++){ //state transfer
            for(j = 0; j < i; j++){
                if(s.charAt(i)!=s.charAt(j)) dp[j][i] = false;
                else if(j+1 == i) dp[j][i] = true;
                else dp[j][i] = dp[j+1][i-1];
                
                if(dp[j][i] && i-j+1 > maxLen){
                    maxLen = i-j+1;
                    start = j;
                }
            }
        }
        
        return s.substring(start, start+maxLen);
    }
}

 

Solution II: 动态规划。p[i]取决于p[i_mirror]

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;
    }
}

 

posted on 2016-05-10 11:07  joannae  阅读(187)  评论(0编辑  收藏  举报

导航