求字符串的回文子序列个数

求字符串的回文子序列个数

题目描述
求一个长度不超过15的字符串的回文子序列个数(子序列长度>=1)。

输入描述
输入一个长度不超过15的字符串,字符串均由小写字母表示

输出描述
输出其回文子序列个数

样例输入
abaa

样例输出
10

注释
本例中其所有回文子序列为:
a,b,a,a,aba,aba,aa,aa,aa,aaa
一个字符串的子序列是指在原字符串上去除某些字符但不破坏余下元素的相对位置(在前或在后)而形成的新字符串。

解题思路:

设字符串为str,长度为len,dp[i][j]表示第i到第j个字符间的最长子序列的长度(i<=j),则:状态初始条件: dp[j][j]=1 (j=0:n-1)
对于任意字符串,如果头尾字符不相等,则字符串的回文子序列个数=去掉头的字符串的回文子序列个数+去掉尾的字符串的回文子序列个数-去掉头尾的字符串的回文子序列个数; if(str[i]!=str[j]) dp[i][j]=dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
如果头尾字符相等,则字符串的回文子序列个数=去掉头的字符串的回文子序列个数+去掉尾的字符串的回文子序列个数+ 1;
dp[i][j]=dp[i+1][j] + dp[i][j-1] +1 if(str[i]==str[j];

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int search(string str) { // num of palindrome subsequence
	int len = str.length();
	vector<vector<int>> dp(len, vector<int>(len));	//creat two-dimensional array for len*len
	for (int j = 0; j < len; j++) { //from front to back
		dp[j][j] = 1;
		for (int i = j - 1; i >= 0; i--) { //from the back to the front
			dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
            if(str[i]==str[j])
                dp[i][j]+=1+dp[i+1][j-1];
		}
	}
	return dp[0][len - 1];
}

int main()
{
	string str;
	cout << "Plz enter the num of palindrome subsequence: ";
	cin >> str;
	if (str.size() > 15)  return false;
	int num = search(str);
	cout << "The num of palindrome subsequence is: " << num << endl;
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值