最长回文子串(动态规划)
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
示例 2:
输入: “cbbd”
输出: “bb”
class Solution {
public:
string longestPalindrome(string s) {
if(s.length() < 2) {
return s;
}
int length = s.length();
string result;
bool dp[length][length];
for(int j = 0; j < length; j++) {
for(int i = 0; i <= j; i++) {
dp[i][j] = s[i] == s[j] ? ((j - i <= 2) || dp[i + 1][j - 1]) : false;
if(dp[i][j] && j - i + 1 > result.length()) {
result = s.substr(i, j - i + 1);
}
}
}
return result;
}
};
传送门-https://leetcode-cn.com/problems/longest-palindromic-substring/