LeetCode C++ 5. Longest Palindromic Substring【String/动态规划】中等

Given a string s , find the longest palindromic substring in s . You may assume that the maximum length of s is 1000 .

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

题意:求出最长的回文子串。


思路:这里先写动态规划的思路。以后更新中心扩展法和Manacher的写法。

Java代码:

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() <= 1) return s;
        int len = s.length(), mx = -1, b = 0, e = len;
        //dp[i][j]表示s[i,j]区域是否是回文子串,是的话它的长度是多少
        int[][] dp = new int[len][len];

        for (int i = len - 1; i >= 0; --i) {
            for (int j = i; j < len; ++j) {
                //子串的s[i]==s[j]
                if (s.charAt(i) == s.charAt(j)) {
                    //特殊情况:子串大小为1,2,3时必然回文
                    if (j - i <= 2) dp[i][j] = j - i + 1;
                    //dp[i+1][j-1]!=0表示s[i+1,j-1]是回文子串
                    else if (dp[i + 1][j - 1] != 0) dp[i][j] = dp[i + 1][j - 1] + 2;
                } 
                //超出之前得到的最大回文子串长度
                if (dp[i][j] > mx) {
                    mx = dp[i][j];
                    b = i;
                    e = j + 1;
                }
            }
        }
        return s.substring(b, e);
    }
}

你可能感兴趣的:(LeetCode,字符串,动态规划)