5. Longest Palindromic Substring
Medium
4380400FavoriteShare
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
这题的状态转移方程实在是没想明白,看来好久解析才看懂,附上博主原文地址
先附上作者原文地址:https://blog.csdn.net/small__snail__5/article/details/80310615
#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length();
int **dp = new int*[len+1];
for(int i=0;i<len+1;i++){
dp[i] = new int[len+1];
}
for(int i=0;i<len+1;i++){
for(int j=0;j<len+1;j++){
dp[i][j] = 0;
}
}
/* j+1 > j+i-1 ----> 即当i<2的时候才有可能满足 j+1 > j+i-1*/
for(int j=0;j<len;j++){
dp[j][j] = 1;
dp[j+1][j] = 1;
}
int left=0,right=0;
for(int i=1;i<len;i++){
for(int j=0;j+i<len;j++){
if(s[j]==s[j+i] && dp[j+1][j+i-1]==1){
left = j;
right = j+i;
dp[left][right] = 1;
}
}
}
int res_len = right - left + 1;
string res = s.substr(left, res_len);
return res;
}
};
int main(){
string str = "cbbd";
Solution *ps = new Solution();
string res = ps->longestPalindrome(str);
cout<<res<<endl;
system("pause");
return 0;
}