5. Longest Palindromic Substring

来源:互联网 发布:淘宝刷单工作室 编辑:程序博客网 时间:2024/06/17 20:51

转自:https://www.cnblogs.com/grandyang/p/4464476.html

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"

       用动态规划Dynamic Programming来解,根Palindrome Partitioning II 拆分回文串之二的解法很类似,我们维护一个二维数组dp,其中dp[i][j]表示字符串区间[i, j]是否为回文串,当i = j时,只有一个字符,肯定是回文串,如果i = j + 1,说明是相邻字符,此时需要判断s[i]是否等于s[j],如果i和j不相邻,即i - j >= 2时,除了判断s[i]和s[j]相等之外,dp[j + 1][i - 1]若为真,就是回文串,通过以上分析,可以写出递推式如下:

dp[i, j] = 1                                              if i == j           = s[i] == s[j]                                 if j = i + 1           = s[i] == s[j] && dp[i + 1][j - 1]    if j > i + 1      

这里有个有趣的现象就是如果我把下面的代码中的二维数组由int改为vector<vector<int> >后,就会超时,这说明int型的二维数组访问执行速度完爆std的vector啊,所以以后尽可能的还是用最原始的数据类型吧。

class Solution {public:       string longestPalindrome(string s) {int n = s.size();int **p;p = new int *[n]; for (int i = 0; i < n; i++){ p[i] = new int[n]; memset(p[i], 0, n * sizeof(int));}       int begin = 0, end = 0 , maxlen = 0;    for (int j = 0; j < n; j++){         p[j][j] = 1;for (int i = 0; i < j; i++){ if (j - i < 2 && s[j] == s[i])  p[i][j] = 1;else if (j - i >= 2 && s[j] == s[i] && p[i + 1][j - 1]) p[i][j] = 1; if (p[i][j] && j - i + 1 > maxlen){maxlen = j - i + 1; begin = i; end = j;}}}for (int i = 0; i < n; i++) {delete[] p[i];p[i] = NULL; //不要忘记,释放空间后p[i]不会自动指向NULL值,还将守在原处,只是释放内存而已,仅此而已。}return s.substr(begin, end - begin + 1);}    };






原创粉丝点击