LeetCode:Longest Palindromic Substring

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.

动态规划解法 

T(n) = O(n^2)  ,S(n) = O(n^2);

Solution:

public class Solution {
    private static int MAX_LENGH = 1000;
    public String longestPalindrome(String s) {
        char[] ch = s.toCharArray();
        int len = s.length();
        int maxLen = 1;
        int longestBegin = 0;
        boolean[][] table = new boolean[len+1][len+1];
        // Arrays.fill(table,false);
        
        for(int i = 0; i < len; i++){
            table[i][i] = true;
        }
        for(int i = 0; i < len-1; i++){
            if(ch[i] == ch[i+1]){
                table[i][i+1] = true;
                longestBegin = i;
                maxLen = 2;
            }
        }
        for(int l = 3 ; l <= len; l++){
            for(int i = 0; i< len - l+1; i++){
                int j = i + l -1;
                if(ch[i] == ch[j] && table[i+1][j-1]){
                    table[i][j] = true;
                    maxLen = l;
                    longestBegin = i;
                }
            }
        }
        return s.substring(longestBegin,longestBegin + maxLen);
    }
}

 

O(n) 线性时间复杂度算法

极其酷炫掉渣天的方法

http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

 

posted @ 2014-06-28 21:20  andyqee  阅读(164)  评论(0编辑  收藏  举报