class Solution {
public:
string longestPalindrome(string s) {
//init
int n = s.length();
vector<vector<int>> dp(n, vector<int>(n, 0));
//travel
int maxLength = 0;
pair<int, int> temp = {};
for(int i = n - 1; i >= 0; i--){
for(int j = i; j < n; j++){
if(s[i] == s[j]){
if(j == i){
dp[i][j] = 1;
}else if(j - i == 1){
dp[i][j] = 2;
}else if(j - i > 1 && dp[i + 1][j - 1] > 0){
dp[i][j] = dp[i + 1][j - 1] + 2;
}
if(maxLength < dp[i][j]){
maxLength = max(maxLength, dp[i][j]);
temp = {i, j};
}
}
}
}
return s.substr(temp.first, maxLength);
}
};
LeetCode Hot100 5.最长回文子串
最新推荐文章于 2024-09-12 13:53:33 发布