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 <= 2ij之间只有一个元素。
循环每次i - j > end - start的时候,都要更新子串更大的情况。Time和space都是O(n^2)

补一种中点延展的方法:循环字符串的每个字符,以该字符为中心,若两边为回文,则向两边继续延展。如此,每个字符必对应一个最长回文串。循环返回长度最长的回文串即可。

Solution

DP

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

方法二:中点延展

public class Solution {
    String longest = "";
    public String longestPalindrome(String s) {
        for (int i = 0; i < s.length(); i++) {
            helper(s, i, 0);
            helper(s, i, 1);
        }
        return longest;
    }
    public void helper(String s, int i, int os) {
        int left = i, right = i + os;
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        String cur = s.substring(left+1, right);
        if (cur.length() > longest.length()) {
            longest = cur;
        }
    }
}

2018-02-03 Added some comments, same thoughts as solution 2

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 2) return s;
        //return as result
        String longest = s.substring(0, 1);
        for (int i = 0; i < s.length()-1; i++) {
            //get 'ABA' type palindrome
            String cur = getPalindrome(s, i, i);
            //get 'ABBA' type palindrome, and compare its length with 'ABA' type
            if (s.charAt(i+1)==s.charAt(i)) {
                String temp = getPalindrome(s, i, i+1);
                cur = cur.length() > temp.length() ? cur : temp;
            }
            //update longest with cur
            longest = longest.length() > cur.length() ? longest : cur;
        }
        return longest;
    }
    public String getPalindrome(String s, int left, int right) {
        while (left > 0 && right < s.length()-1 && s.charAt(left-1) == s.charAt(right+1)) {
            left--;
            right++;
        }
        //careful with the right bound
        return s.substring(left, right+1);
    }
}

linspiration
161 声望53 粉丝