题目
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”
算法思路
本周继续学习动态规划的问题,本题要求寻找最长的回文子串,也是比较经典的动态规划问题。
我们要找出最长的回文子串,需要判断各个子串是否是回文串
分解子问题的状态方程
P( i,j ) = P(i+1,j-1) and S[i] == S[j]
P( i,j )是个布尔类型,表示子串S[i]…S[j]是否是回文串。
S( i )表示原字符串第i个字符。
C++代码
class Solution {
public:
string longestPalindrome(string s) {
if (s.size() == 0)
{
return "";
}
bool judge[s.size()][s.size()] = {false};
int result[2] = {0};
for (int i = 0; i < s.size(); ++i)
{
judge[i][i] = true;
}
for (int i = 1; i < s.size(); ++i)
{
for (int j = 0; j < s.size()-i; ++j)
{
if ((i == 1 && s[j] == s[i+j]) || (judge[j+1][i+j-1] && s[j] == s[i+j]))
{
judge[j][i+j] = true;
if (i > result[1]-result[0])
{
result[0] = j;
result[1] = i+j;
}
}
else
{
judge[j][i+j] = false;
}
}
}
return s.substr(result[0],result[1]-result[0]+1);
}
};