Given a string S, find the longest palindromic substring in S. You may assume that the maximum
length of S is 1000, and there exists one unique longest palindromic substring.
最长回文串。
简单思路 f(i,j) 切分,然后俩头向中间扫,暴力,耗时!
再者用动归,上面很多重复的中间串。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string longestPalindrome(string s) ;
int main()
{
string s;
cin>>s;
cout<<longestPalindrome(s)<<endl;
return 0;
}
string longestPalindrome(string s)
{
vector<vector<bool>> dp(s.size()+1,vector<bool>(s.size()+1,false));
int max_len = 0;
int low = 0;
for(int i = 1;i <= s.size();i++)
{
for(int j = 1;j <= i;j++)
{
if(s[i-1] == s[j-1]&&((i-j < 2) || dp[j+1][i-1]))
{
if((i - j + 1) > max_len)
{
max_len = i - j + 1;
low = j-1;//位置
}
dp[j][i] = true;
//cout<<j<<" "<<i<<" "<<max_len<<endl;
}
}
}
return s.substr(low,max_len);
}