lc 5 Longest Palindromic Substring
5 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"
DP Accepted
看题目的标题就应该可以猜到这一题可以借助动态规划求解最优解。用数组str[i][j]表示从第i-1到第j-1个的子串是一个回文。首先,对于所有单个字符来说,本身就是一个回文,长度为1;而对于两个连在一起的字符来说,如果相同,那么回文长度就为2。以上是问题最简单的例子,考虑复杂的情况,依次寻找长度为3以上的回文,如果首尾相同且首尾之间是回文,则更新记录的回文长度和起始位置。
class Solution {
public:
string longestPalindrome(string s) {
int begin = 0, len = s.size(), max = 1;
bool str[1000][1000] = {false};
for (int i = 0; i < len; i++) str[i][i] = true;
for (int i = 0; i < len-1; i++) {
if (s[i] == s[i+1]) {
max = 2;
begin = i;
str[i][i+1] = true;
}
}
for (int l = 3; l <= len; l++) {
for (int i = 0; i < len-l+1; i++) {
int j = l+i-1;
if (s[i] == s[j] && str[i+1][j-1]) {
max = l;
begin = i;
str[i][j] = true;
}
}
}
return s.substr(begin, max);
}
};