回文子序列和回文字符串
回文子序列和回文字符串是不同的概念。
最长回文子序列
LeetCode516题:
方法一:记忆化搜索
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int GetPalindromicSequence(string s,int i, int j, int ret[100][100])
{
if (ret[i][j] != 0) return ret[i][j];
if (i == j) return ret[i][j] = 1;
if (i == j-1) return ret[i][j] = (s[i]==s[j]?2:1);
if (s[i] == s[j])
{
return ret[i][j] = 2 + GetPalindromicSequence(s, i + 1, j - 1, ret);
}
else
{
return ret[i][j] = max(GetPalindromicSequence(s, i, j - 1, ret), GetPalindromicSequence(s, i + 1, j, ret));
}
}
int main()
{
string str = "";
std::cout << "Please input the string!\n";
cin >> str;
int iLen = str.length();
int ret[100][100] = { 0 };
cout << "The max length of Palindromic Seqence is: " << GetPalindromicSequence(str, 0, iLen - 1, ret) << endl;
for (int i = 0; i < iLen; ++i)
{
for (int j = 0; j < iLen; ++j)
{
cout << ret[i][j];
}
cout << endl;
}
}
输入:abcdbf
结果:
The max length of Palindromic Seqence is: 3
011133
001133
000111
000011
000001
000000
输入:cbdbaebfbg
结果:
The max length of Palindromic Seqence is: 5
0113333355
0013333355
0011113333
0000113333
0000011133
0000001133
0000000133
0000000111
0000000001
0000000000
其中对角线上ret[[2]][[2]]和ret[[7]][[7]]的值为1,是因为s[[1]]==s[[3]]则ret[[1]][[3]]=2+ret[[2]][[2]];和s[6]==s[8]则ret[6][8]]=2+ret[7][7];而当ij时,ret[i][j]=1。
方法二:动态规划
dp[i][j]的含义是原字符串从第i位到第j位可以构成最长回文子序列的长度
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int longestPalindromicSubseq(string s)
{
int n = s.length();
int dp[100][100] = { 0 };
for (int i = n - 1; i >= 0; --i)
{
dp[i][i] = 1;
for (int j = i + 1; j < n; ++j)
{
if (s[i] == s[j])
{
dp[i][j] = 2 + dp[i + 1][j - 1];
}
else
{
dp[i][j] = max(dp[i ][j - 1], dp[i + 1][j]);
}
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cout << dp[i][j];
}
cout << endl;
}
return dp[0][n-1];
}
int main()
{
string str = "";
std::cout << "Please input the string!\n";
cin >> str;
cout << "The max length of Palindromic Seqence is: " << longestPalindromicSubseq(str) << endl;
}
输入:abcdbf
结果:
111133
011133
001111
000111
000011
000001
The max length of Palindromic Seqence is: 3
输入:cbdbaebfbg
结果:
1113333355
0113333355
0011113333
0001113333
0000111133
0000011133
0000001133
0000000111
0000000011
0000000001
The max length of Palindromic Seqence is: 5