题目来源:https://leetcode.com/problems/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, and there exists one unique longest palindromic substring.
动态规划,类似于lcs的解法,数组flag[i][j]记录s从i到j是不是回文
首先初始化,i>=j时,flag[i][j]=true,这是因为s[i][i]是单字符的回文,当i>j时,为true,是因为有可能出现flag[2][1]这种情况,比如bcaa,当计算s从2到3的时候,s[2]==s[3],这时就要计算s[2+1] ?= s[3-1],总的来说,当i>j时置为true,就是为了考虑j=i+1这种情况。
接着比较s[i] ?= s[j],如果成立,那么flag[i][j] = flag[i+1][j-1],否则直接flag[i][j]=false
c++代码:
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length(), max = , ss = , tt = ;
bool flag[len][len];
for (int i = ; i < len; i++)
for (int j = ; j < len; j++)
if (i >= j)
flag[i][j] = true;
else flag[i][j] = false;
for (int j = ; j < len; j++)
for (int i = ; i < j; i++)
{
if (s[i] == s[j])
{
flag[i][j] = flag[i+][j-];
if (flag[i][j] == true && j - i + > max)
{
max = j - i + ;
ss = i;
tt = j;
}
}
else flag[i][j] = false;
}
return s.substr(ss, max);
}
};