[LintCode] Longest Palindrome Substring

java 4 2016-02-29 13:03
女装

Problem

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.

Example

Given the string = "abcdzdcab", return "cdzdc".

Challenge

O(n2) time is acceptable. Can you do it in O(n) time.

Note

动规好题。
注意.substring(start, end)是左闭右开区间,所以返回值里end+1
if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || dp[j+1][i-1]))这一句,要理解i - j <= 2其实是ij之间只有一个元素的情况。
循环里每一次i - j > end - start的时候,都要更新为子串更大的情况。Time和space都是O(n^2)

Solution

public class Solution {
    public String longestPalindrome(String s) {
        // Write your code here
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        int start = 0, end = 0;
        for (int i = 0; i < len; i++) {
            for (int j = 0; j <= i; j++) {
                if (s.charAt(i) == s.charAt(j) && (i - j <= 2 || dp[j+1][i-1])) {
                    dp[j][i] = true;
                    if (end - start < i - j ) {
                        start = j;
                        end = i;
                    }
                }
            }
        }
        return s.substring(start, end+1);
    }
}
女装
文章评论