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"


以下说明转载自:
https://leetcode.com/problems/longest-palindromic-substring/discuss/147548/Direct-c%2B%2B-DP
My code is based on the solution Approach3.
First initialize a matrix P, which is used to store if the substring is palindromic. Now we should fill the block of "S(i) = S(i)" and "S(i) = S(i+1)", the basic case that we can't find any substring in it. Then with this matrix, we can decide if a string is palindromic by if its substring is palindromic and if its start letter equals end letter.
The image below is a matrix for string "abbc". For example, start with the first "b" and end with "c" tells if substring "bbc" is palindromic. What we need to do next is filling the "??" block, only half of the matrix is used.
After initialization, we can decide if a string is palindromic by its substring and newly added letters, shown below.
If we want to decide the block pointed by the arrow("abb"), we should look up [b,b], which is substring "b", and see if ("a"=="b"). As shown, "a"!="b", so "abb" is not palindromic.
After that, it seems like this:
Last, we have got this matrix, but we still need to find which is the longest palindromic substring.
My method is only traversing it, return the longest substring. So the result in this example is "bb".
class Solution {
public:
string longestPalindrome(string s) {
int len = s.size();
if (len == 0) return "";
bool** symbol = new bool*[len];
for (int i = 0; i < len; i++)
symbol[i] = new bool[len];
for (int i = 0; i < len; i++)
for (int j = 0; j < len; j++)
symbol[i][j] = false;
// initialize symbol[len][len]
for (int i = 0; i < len; i++) {
symbol[i][i] = true;
if (i == len - 1) break;
symbol[i][i+1] = (s[i] == s[i+1]);
}
// dynamic programming
for (int i = len - 2; i >= 0; i--) {
int start = i + 2;
for (int j = start; j < len; j++) {
symbol[i][j] = (symbol[i+1][j-1] && s[i] == s[j]);
}
}
// get max length string
int max = 0;
string maxstr = "";
for (int i = 0; i < len; i++) {
int count = 0;
for (int j = i; j < len; j++) {
if (symbol[i][j] == true) {
count = j - i + 1;
}
}
if (count > max) {
max = count;
maxstr = s.substr(i, count);
}
}
return maxstr;
}
};
本文介绍了一种基于动态规划的算法,用于寻找给定字符串中的最长回文子串。通过初始化矩阵并填充基本的回文情况,算法能判断任意子串是否为回文,并最终确定最长的回文子串。
239

被折叠的 条评论
为什么被折叠?



