leetcode 73: Longest Palindromic Substring

Longest Palindromic SubstringNov 11 '11

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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int sz = s.length();
        
        if(sz<=1) return s;
        
        int[][] d = new int[sz][sz];
        
        for(int i=0; i<sz; i++) {
            d[i][i] = 1;
        }
        
        int longest = 1;
        int start = 0;
        
        for(int i=0; i<sz-1; i++) {
            if( s.charAt(i) == s.charAt(i+1) ) {
                d[i][i+1] = 2;
                if( d[i][i+1] > longest) {
                    longest = d[i][i+1];
                    start = i;
                }
            }
        }
        
        for(int len=2; len<sz; len++) {
            for(int i=0; i<sz-len; i++){
                int j=i+len;
                
                if( s.charAt(i) == s.charAt(j)  && d[i+1][j-1]!=0 ) {
                    d[i][j] = len+1;
                    if( d[i][j]>longest ) {
                        longest = d[i][j];
                        start = i;
                    }    
                } else {
                    d[i][j] = 0;
                }
            }
        }
        
        return s.substring(start, start+longest);
    }
}


 

posted @ 2013-02-14 09:32  西施豆腐渣  阅读(132)  评论(0编辑  收藏  举报