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.
使用动态规划,这样可以把时间复杂度降到O(N²),空间复杂度也为O(N²)。做法如下:
首先,写出动态转移方程。
Define P[ i, j ] ← true iff the substring Si … Sj is a palindrome, otherwise false.
P[ i, j ] ← ( P[ i+1, j-1 ] and Si = Sj ) ,显然,如果一个子串是回文串,并且如果从它的左右两侧分别向外扩展的一位也相等,那么这个子串就可以从左右两侧分别向外扩展一位。
其中的base case是
P[ i, i ] ← true
P[ i, i+1 ] ← ( Si = Si+1 )
然后,看一个例子。
假设有个字符串是adade,现在要找到其中的最长回文子串。使用上面的动态转移方程,有如下的过程:
按照红箭头->黄箭头->蓝箭头->绿箭头->橙箭头的顺序依次填入矩阵,通过这个矩阵记录从i到j是否是一个回文串。
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
int longestBegin = 0;
int maxLen = 1;
bool table[1000][1000] = {false};
for (int i = 0; i < n; i++) {
table[i][i] = true;
}
for (int i = 0; i < n-1; i++) {
if (s[i] == s[i+1]) {
table[i][i+1] = true;
longestBegin = i;
maxLen = 2;
}
}
for (int len = 3; len <= n; len++) {
for (int i = 0; i < n-len+1; i++) {
int j = i+len-1;
if (s[i] == s[j] && table[i+1][j-1]) {
table[i][j] = true;
longestBegin = i;
maxLen = len;
}
}
}
return s.substr(longestBegin, maxLen);
}
};
改进版:
class Solution {
public:
string longestPalindrome(string s) {
int n = s.length();
if(n<=1) return s;
int index1=0;
int max=0;
int c,j;
for (int i = 0; i < n; ++i)
{
for (j = 0; (i-j)>=0 && (i+j)<n; ++j)
{
if(s[i-j] != s[i+j])
break;
c = j*2+1;
}
if(c>max)
{
max = c;
index1 = i-j+1;
}
for(j = 0; (i-j)>=0 && (i+j+1)<n; ++j)
{
if(s[i-j]!=s[i+j+1])
break;
c = j*2+2;
}
if (c>max)
{
max = c;
index1 = i-j+1;
}
}
return s.substr(index1, max);
}
};