回文子序列和回文字符串

回文子序列和回文字符串

回文子序列和回文字符串是不同的概念。

最长回文子序列

LeetCode516题:
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值