class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
vector<vector<int>> dp(n,vector<int>(n,0));
for(int i=0;i<n;i++){
dp[i][i]=true;
}
for (int L = 2; L <= n; L++) {
for (int i = 0; i < n; i++) {
int j = L + i - 1;
if (j >= n) {
break;
}
if (s[i] != s[j]) {
dp[i][j] = false;
} else {
if (j - i < 3) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i + 1][j - 1];
}
}
}
}
int maxLen = 0;
int index = 0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(dp[i][j]==true&&(j-i+1)>maxLen){
maxLen = j-i+1;
index = i;
}
}
}
return s.substr(index,maxLen);
}
};
5. 最长回文子串
最新推荐文章于 2024-03-24 12:07:27 发布