LeetCode5_最长回文子串

使用动态规划的方法。

确定动态方程;

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         int length = s.length();
 5         if(length <2){
 6             return s;
 7         }
 8 
 9         vector<vector<int>> dp(length,vector<int>(length,0));
10         int maxlength = 1;
11         int resi=0,resj=0;
12         for(int i = length-1; i>=0;i--){
13             for(int j = i; j<=length-1;j++){
14                 if(i==j) {                 //长度为1
15                     dp[i][j] = 1;
16                     continue;
17                 }
18 
19                 if(s[i]==s[j] && j-i<=2) {  //长度小于等于3
20                     dp[i][j] = 1;
21                     if(dp[i][j]==1&&(j-i+1)>maxlength){
22                         maxlength = j-i+1;
23                         resi = i;
24                         resj = j;
25                     }
26                     continue;
27                 }
28                 if(s[i]==s[j]){
29                     dp[i][j]=dp[i+1][j-1];
30                     if(dp[i][j]==1&&(j-i+1)>maxlength){
31                         maxlength = j-i+1;
32                         resi = i;
33                         resj = j;
34                     }
35                 }
36 
37             }
38         }
39         return s.substr(resi,(resj-resi+1));
40     }
41 };

猜你喜欢

转载自www.cnblogs.com/grooovvve/p/12369803.html