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.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"

分析

1. 题目要求

给出一个字符串,求解出该字符串的最长回文子串。

2. 求解方法

可以用暴力求解的方法,遍历出该字符串的所有子串,然后判断各个子串是否为回文子串,输出最大的回文子串,该方法的时间复杂度为O(n^3)。

也可以用动态规划的方法来求解其最长回文子串。其时间复杂度为O(n^2)。

使用一个 bool 类型的二维数组p,p[i][j] 表示从 i 到 j 的子串是否为回文子串。

p[i][j] = {s[i] == s[j] , i - j <= 1; s[i] == s[j] && p[i + 1][j - 1];}

3. 代码如下

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length();
        int max_len = 0;
        int start = 0;
        bool **arr = new bool*[len];
        for (int i = 0; i < len; i++) {
            arr[i] = new bool[len];
            for (int j = 0; j < len; j++) {
                arr[i][j] = false;
            }
        }
        // 以 j 为起点, i 为结点的子串
        for (int i = 0; i < len; i++) {
            for (int j = 0; j <= i; j++) {
                if (i - j < 2) {
                    arr[j][i] = (s[i] ==  s[j]);
                } else {
                    arr[j][i] = (s[i] == s[j] && arr[j + 1][i - 1]);
                }
                if (arr[j][i] == true && max_len < i-j+1) {
                    max_len = i - j + 1;
                    start = j;
                }
            }
        }
        return s.substr(start, max_len);
    }
};
还有一种时间复杂度更低的 Manacher法,以后再说。

你可能感兴趣的:(算法分析,Leetcode)