Longest Palindromic Substring

来源:互联网 发布:压缩感知 知乎 编辑:程序博客网 时间:2024/06/09 14:46

reference http://www.programcreek.com/2013/12/leetcode-solution-of-longest-palindromic-substring-java/


soln1 O(n^2) time, O(1) space

public class Solution {
    public String longestPalindrome(String s) {
        if(s==null) return null;
        if(s.length()==1) return s;
        
        String longest = s.substring(0,1); // because at least there are 2 elements in s
        
        for(int i=0;i<s.length();i++){
            String tmp = helper(s, i, i); // 中心对称外延,延伸出来的tmp为奇数位长度
            if(longest.length()<tmp.length())
                longest = tmp;
            
             tmp = helper(s,i, i+1); //中心对称外延,tmp为偶数长度
            if(longest.length()<tmp.length())
                longest = tmp;
        }
        
        return longest;
        
    
    }
    
    public String helper(String s, int b, int e){
        while(b>=0 && e< s.length()  && s.charAt(b)==s.charAt(e)){
            b--;
            e++;
        }
        return s.substring(b+1, e);
    }
}


soln2 DP

http://www.geeksforgeeks.org/longest-palindrome-substring-set-1/

http://www.programcreek.com/2013/12/leetcode-solution-of-longest-palindromic-substring-java/


会lte, 代码如下:

        String res = null;
        int len = s.length();
        int[][] table = new int[len][len]; // a boolean table, record from i to j is there a palindromic string?
        int MaxLen = 1;
        
        for(int i=0;i<len;i++){
            table[i][i]=1;
        }
        
        for(int i=0;i<len-1;i++){
            if(s.charAt(i)==s.charAt(i+1)){
                // MaxLen=2;
                table[i][i+1]=1;
                res = s.substring(i,i+2);
            }
            // else{
            //     table[i][i+1]=0;
            // }
        }
        
        for(int L=3; L<=len; L++){
            for(int i=0;i<len-L+1  ;i++){
                int j = L+i-1;
                if(  s.charAt(i)==s.charAt(j) && table[i+1][j-1]==1){
                    table[i][j]=1;
                    if( L>MaxLen ){
                        MaxLen=L;
                        res = s.substring(i,j+1);
                    }
                }else{
                        table[i][j]=0;
                    } 
                }
            }
        return res;
        
    }
}


0 0