动态规划算法求最长回文子串

回文串就是正着读和反着读一样的字符串,如“abba”,"abcba",最长回文子串是字符串的子串中最长的属于回文串的子串。如字符串"abbaabccba"的最长回文子串为"abccba",本文采用动态规划算法来查找最长回文子串,算法时间复杂度为O(n²)。设状态dp[j][i]表示索引j到索引i的子串是否是回文串。则易得转移方程如下:


则dp[j][i]为true时表示索引j到索引i形成的子串为回文子串,且子串起点索引为i,长度为j+i-1。

具体程序如下:

[cpp]   view plain  copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. #include <string>  
  4. using namespace std;  
  5. class Solution {  
  6. public:  
  7.     string longestPalindrome(string s) {  
  8.         const int n=s.size();  
  9.         bool dp[n][n];  
  10.         fill_n(&dp[0][0],n*n,false);  
  11.         int max_len=1; //保存最长回文子串长度  
  12.         int start=0;//保存最长回文子串起点  
  13.         for(int i=0;i<s.size();++i)  
  14.         {  
  15.             for(int j=0;j<=i;++j)  
  16.             {  
  17.                 if(i-j<2)  
  18.                     dp[j][i]=(s[i]==s[j]);  
  19.                 else  
  20.                     dp[j][i]=(s[i]==s[j] && dp[j+1][i-1]);  
  21.                 if(dp[j][i] && max_len<(i-j+1))  
  22.                 {  
  23.                     max_len=i-j+1;  
  24.                     start=j;  
  25.                 }  
  26.             }  
  27.         }  
  28.         return s.substr(start,max_len);  
  29.     }  
  30. };  
  31.   
  32. int _tmain(int argc, _TCHAR* argv[])  
  33. {  
  34.     string input;  
  35.     Solution sln;  
  36.     while(cin>>input)  
  37.     {  
  38.         cout<<"最长回文子串为:"<<sln.longestPalindrome(input)<<endl;  
  39.     }  
  40.     return 0;  
  41. }  

猜你喜欢

转载自blog.csdn.net/faker_wang/article/details/80806255
今日推荐