Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
题目要求最长回文子串,用动态规划。
dp[j][i]表示从下标j到i之间的字符串是否是回文的。
j==i时,dp[j][i] = 1
i - j < 2时,s[j]与s[i]相邻,dp[j][j] = s[j] == s[i]
i - j >= 2时,dp[j][j] = (s[j] == s[i] && dp[j+1][i-1])
当找到一个回文子串时,记录其下标范围和长度,并更新最长回文子串长度len。
字符串遍历结束后,left即为最长回文子串的起始位置,len为子串长度,调用s.substr(left, len)就得到了最长回文子串。
class Solution {
public:
string longestPalindrome(string s) {
int dp[s.size()][s.size()] = {0};
int left = 0, right = 0, len = 1;
if(s.size() == 0 || s.size() == 1)
return s;
for(int i = 1; i < s.size(); i++){
for(int j = 0; j < i; j++){
dp[j][i] = (s[j] == s[i] && (i - j < 2 || dp[j+1][i-1]));
if(dp[j][i] && len < i - j + 1){
left = j;
right = i;
len = right - left + 1;
}
}
dp[i][i] = 1;
}
return s.substr(left, len);
}
};