回文子序列_计算回文子序列的总数

回文子序列

Problem statement:

问题陈述:

Given a string str, find total number of possible palindromic sub-sequences. A sub-sequence does not need to be consecutive, but for any xixj i<j must be valid in the parent string too. Like "icl" is a subsequence of "includehelp" while "ple" is not.

给定字符串str ,找到可能的回文子序列的总数。 子序列不必是连续的,但是对于任何x i x j i <j在父字符串中也必须有效。 像“ icl”一样,是“ includehelp”的子序列,而“ ple”则不是。

Input:

输入:

The first line of input contains an integer T, denoting the no of test cases then T test cases follow. Each test case contains a string str.

输入的第一行包含一个整数T ,表示测试用例的数量,然后是T个测试用例。 每个测试用例都包含一个字符串str

Output:

输出:

For each test case output will be an integer denoting the total count of palindromic subsequence which could be formed from the string str.

对于每个测试用例,输出将是一个整数,表示回文子序列的总数,该总数可以由字符串str形成。

Constraints:

限制条件:

1 <= T <= 100
1 <= length of string str <= 300

Example:

例:

Input:
Test case: 2
First test case:
Input string:
"aaaa"
Output:
Total count of palindromic subsequences is: 15
Second test case:
Input string:
"abaaba"
Output:
Total count of palindromic subsequences is: 31

Explanation:

说明:

Test case 1:

测试用例1:

Input: "aaaa"

输入:“ aaaa”

The valid palindromic subsequences are shown below,

有效回文子序列如下所示,

Marked cells are character taken in subsequence:

标记的单元格是子序列中的字符:

Count=1

计数= 1

Count total number of Palindromic Subsequences (1)

Count=2

计数= 2

Count total number of Palindromic Subsequences (2)

Count=3

计数= 3

Count total number of Palindromic Subsequences (3)

Count=4

计数= 4

Count total number of Palindromic Subsequences (4)

Count=5

计数= 5

Count total number of Palindromic Subsequences (5)

Count=6

计数= 6

Count total number of Palindromic Subsequences (6)

Count=7

计数= 7

Count total number of Palindromic Subsequences (7)

Count=8

计数= 8

Count total number of Palindromic Subsequences (8)

Count=9

计数= 9

Count total number of Palindromic Subsequences (9)

Count=10

数= 10

Count total number of Palindromic Subsequences (10)

Count=11

数= 11

So on...
Total 15 palindromic sub-sequences
Actually in this case since all the character is same each and every subsequence is palindrome here.
For the second test case
Few sub-sequences can be
"a"
"b"
"a"
"aba"
So on
Total 31 such palindromic subsequences

等等...
总共15个回文子序列
实际上,在这种情况下,由于所有字符都是相同的,每个子序列在这里都是回文。
对于第二个测试用例
很少有子序列可以是
“一个”
“ b”
“一个”
“阿巴”
依此类推
总共31个这样的回文序列

Solution approach

解决方法

This can be solved by using DP bottom up approach,

这可以通过使用DP自下而上的方法来解决,

  1. Initialize dp[n][n] where n be the string length to 0

    初始化dp [n] [n] ,其中n为0的字符串长度

  2. Fill up the base case, Base case is that each single character is a palindrome itself. And for length of two, i.e, if adjacent characters are found to be equal then dp[i][i+1]=3, else if characters are different then dp[i][i+1]=2

    填满基本情况,基本情况是每个单个字符本身都是回文。 对于两个长度,即,如果发现相邻字符相等,则dp [i] [i + 1] = 3 ;否则,如果字符不同,则dp [i] [i + 1] = 2

    To understand this lets think of a string like "acaa"

    要理解这一点,可以考虑一个字符串,例如“ acaa”

    Here

    这里

    dp[0][1]=2 because there's only two palindrome possible because of "a" and "c".

    dp [0] [1] = 2是因为“ a”和“ c”仅可能存在两个回文。

    Whereas for

    鉴于

    dp[2][3] value will be 3 as possible subsequences are "a", "a", "aa".

    dp [2] [3]的值将为3,因为可能的子序列为“ a”,“ a”,“ aa”。

    for i=0 to n
    // for single length characters
    dp[i][i]=1; 
    if(i==n-1)
    break;        
    if(s[i]==s[i+1])
    dp[i][i+1]=3;
    else
    dp[i][i+1]=2;
    end for
    
    
  3. Compute for higher lengths,

    计算更长的长度,

    for len=3 to n
    for start=0 to n-len
    int end=start+len-1;
    // start and end is matching
    if(s[end]==s[start])
    // 1+subsequence from semaining part
    dp[start][end]=1+dp[start+1][end]+dp[start][end-1];
    else
    dp[start][end]=dp[start+1][end]+dp[start][end-1]-dp[start+1][end-1];
    end if
    end for
    end for
    
    
  4. Final result is stored in dp[0][n-1];

    最终结果存储在dp [0] [n-1]中;

So for higher lengths if starting and ending index is the same then we recur for the remaining characters, since we have the sub-problem result stored so we computed that. In case start and end index character are different then we have added dp[start+1][end] and dp[start][end-1] that's similar to recur for leaving starting index and recur for leaving end index. But it would compute dp[start+1][end-1] twice and that why we have deducted that.

因此,对于更大的长度,如果开始索引和结束索引相同,那么我们将重复其余字符,因为我们存储了子问题结果,因此我们对其进行了计算。 如果起始索引和终止索引的字符不同,则我们添加了dp [start + 1] [end]dp [start] [end-1] ,类似于recur离开起始索引和recur离开结束索引。 但是它将两次计算dp [start + 1] [end-1] ,这就是为什么我们要减去它。

For proper understanding you can compute the table by hand for the string "aaaa" to understand how it's working.

为了正确理解,您可以手动计算字符串“ aaaa”的表以了解其工作方式。

C++ Implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;
int countPS(string s)
{
int n = s.length();
int dp[n][n];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < n; i++) {
dp[i][i] = 1;
if (i == n - 1)
break;
if (s[i] == s[i + 1])
dp[i][i + 1] = 3;
else
dp[i][i + 1] = 2;
}
for (int len = 3; len <= n; len++) {
for (int start = 0; start <= n - len; start++) {
int end = start + len - 1;
if (s[end] == s[start]) {
dp[start][end] = 1 + dp[start + 1][end] + dp[start][end - 1];
}
else {
dp[start][end] = dp[start + 1][end] + dp[start][end - 1] - dp[start + 1][end - 1];
}
}
}
return dp[0][n - 1];
}
int main()
{
int t;
cout << "Enter number of testcases\n";
cin >> t;
while (t--) {
string str;
cout << "Enter the input string\n";
cin >> str;
cout << "Total Number of palindromic Subsequences are: " << countPS(str) << endl;
}
return 0;
}

Output:

输出:

Enter number of testcases
2
Enter the input string
aaaa
Total Number of palindromic Subsequences are: 15
Enter the input string
abaaba
Total Number of palindromic Subsequences are: 31

翻译自: https://www.includehelp.com/icp/count-total-number-of-palindromic-subsequences.aspx

回文子序列

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/544927.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Microsoft Azure学习之旅】测试消息队列(Service Bus Queue)是否会丢消息

组里最近遇到一个问题&#xff0c;微软的Azure Service Bus Queue是否可靠&#xff1f;是否会出现丢失消息的情况&#xff1f; 具体缘由如下&#xff0c; 由于开发的产品是SaaS产品&#xff0c;为防止消息丢失&#xff0c;跨Module消息传递使用的是微软Azure消息队列&#xff0…

使用SharedPreferences存储和读取数据

转&#xff1a;http://www.worlduc.com/blog2012.aspx?bid19403392 1、任务目标 &#xff08;1&#xff09;掌握Android中SharedPreferences的使用方法。 2、任务陈述 &#xff08;1&#xff09;运行后&#xff0c;显示如下界面&#xff0c;可以写入和读取SharedPreferences中…

Zookeeper 的 5 大核心知识点!

1 ZooKeeper简介ZooKeeper 是一个开源的分布式协调框架&#xff0c;它的定位是为分布式应用提供一致性服务&#xff0c;是整个大数据体系的管理员。ZooKeeper 会封装好复杂易出错的关键服务&#xff0c;将高效、稳定、易用的服务提供给用户使用。如果上面的官方言语你不太理解&…

PHP | 计算字符串中的单词总数

Given a string and we have to count the total number of words in it. 给定一个字符串&#xff0c;我们必须计算其中的单词总数。 str_word_count() function str_word_count()函数 To find the total number of words in a string, we can use str_word_count() function…

parted分区介绍

简介: 当硬盘或raid后,硬盘大于2T的时候,可以使用parted进行分区; 使用parted的前提是操作系统已经安装部署完成; 大于2T的硬盘在安装部署阶段可以使用raid的虚拟磁盘技术分区,如分出100G安装系统,剩余的在安装系统后,使用parted进行分区; 1.parted非交互式分区: …

SharedPreferences详解

我们在开发软件的时候,常需要向用户提供软件参数设置功能,例如我们常用的微信,用户可以设置是否允许陌生人添加自己为好友.对于软件配置参数的保存,如果是在window下通常我们会采用ini文件进行保存.如果是J2EE下面,我们会采用properties属性文件或者xml进行保存.在我们的Androi…

【视频版】最新版Swagger 3升级指南和新功能体验!

作者 | 王磊来源 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone&#xff09;Swagger 3.0 发布已经有一段时间了&#xff0c;它于 2020.7 月 发布&#xff0c;但目前市面上使用的主流版本还是 Swagger 2…

java treemap_Java TreeMap pollFirstEntry()方法与示例

java treemapTreeMap类pollFirstEntry()方法 (TreeMap Class pollFirstEntry() method) pollFirstEntry() method is available in java.util package. pollFirstEntry()方法在java.util包中可用。 pollFirstEntry() method is used to return and then remove the entry (key-…

各大厂面试高频的面试题新鲜出炉,你能答上几道?

关于生产环境如何配置线程数&#xff0c;还是要根据业务来进行区分&#xff0c;我们时常会听到什么IO密集型、CPU密集型任务...那么这里提一个问题&#xff1a;大家知道什么样的任务或者代码会被认定为IO/CPU密集&#xff1f;又是用什么样的标准来认定IO/CPU密集&#xff1f;如…

c/c++如何获取数组的长度

2019独角兽企业重金招聘Python工程师标准>>> C、C中没有提供 直接获取数组长度的函数&#xff0c;对于存放字符串的字符数组提供了一个strlen函数获取长度&#xff0c;那么对于其他类型的数组如何获取他们的长度呢&#xff1f;其中一种方法是使 用sizeof(array) / s…

JSP JAVA 自定义 错误页面(404,505,500)

当网站页面找不到或者服务器内部出错的时候&#xff0c;我们不想让用户看到默认的那张 404&#xff0c;500 的错误页面&#xff0c;那要是想自己做一张 找不到页面的页面改怎么做呢&#xff1f;在 web .xml 文件中 加入下面的语句就能达到这个效果<error-page><error-…

【送给读者】全新苹果 AirPods,包邮送一套!

为回馈长期以来科创人读者对本栏目的关注支持&#xff0c;本周小编联合了计算机领域八位高质量原创号主一起为大家送出一套 全新苹果AirPods 2代。以下推荐的公号原创率都很高&#xff0c;均为个人IP号&#xff0c;有些小伙伴应该已经关注部分公号。本次抽奖采用第三方抽奖小程…

java 方法 示例_Java扫描仪的hasNextBoolean()方法与示例

java 方法 示例扫描器类的hasNextBoolean()方法 (Scanner Class hasNextBoolean() method) hasNextBoolean() method is available in java.util package. hasNextBoolean()方法在java.util包中可用。 hasNextBoolean() method is used to check whether this Scanners next in…

进程控制(kill)

为什么80%的码农都做不了架构师&#xff1f;>>> kill&#xff1a;终止进程&#xff08;或传送信号到某进程&#xff09; kill [options] [process_ids] kill命令可以发送信号给进程&#xff0c;可以终止&#xff08;terminate&#xff09;&#xff08;默认操作&a…

oracle怎样修改表名、列名、字段类型、添加表列、删除表列

ALTER TABLE SCOTT.TEST RENAME TO TEST1--修改表名 ALTER TABLE SCOTT.TEST RENAME COLUMN NAME TO NAME1 --修改表列名 ALTER TABLE SCOTT.TEST MODIFY NAME1 NUMBER(20) --修改字段类型 ALTER TABLE SCOTT.TEST ADD ADDRESS VARCHAR2(40) --添加表列 ALTER TABLE SCOTT.TEST…

TextArea里Placeholder换行问题

转&#xff1a;http://www.tuicool.com/articles/feYVNf 页面上使用TextArea控件时&#xff0c;会时不时的想给个提示&#xff0c;比如按照一定方式操作之类的。 正常情况下&#xff0c;会使用Placeholder&#xff0c;但这样的提示是不会换行的&#xff0c;无论是用\r\n&…

printstream_Java PrintStream clearError()方法与示例

printstreamPrintStream类clearError()方法 (PrintStream Class clearError() method) clearError() method is available in java.io package. clearError()方法在java.io包中可用。 clearError() method is used to clear the internal error state of this PrintStream. cle…

uniq用法详解

uniquniq命令可以去除排序过的文件中的重复行&#xff0c;因此uniq经常和sort合用。也就是说&#xff0c;为了使uniq起作用&#xff0c;所有的重复行必须是相邻的。uniq语法[rootwww ~]# uniq [-icu]选项与参数&#xff1a;-i &#xff1a;忽略大小写字符的不同&#xff1b;-…

Swagger增强神器:Knife4j!用它轻松实现接口搜索、Word下载、接口过滤...

视频版内容&#xff1a;Swagger 是开发中最常用的框架之一了&#xff0c;但 Swagger 本身又有很多不完善的地方&#xff0c;比如&#xff0c;在众多的接口中查询某一个接口&#xff0c;又或者是把所有的接口导出成 Word 格式等&#xff0c;都无法在 Swagger 中实现。有人可能会…

tohexstring方法_Java Long类toHexString()方法的示例

tohexstring方法长类toHexString()方法 (Long class toHexString() method) toHexString() method is available in java.lang package. toHexString()方法在java.lang包中可用。 toHexString() method is used to represent a hexadecimal string of the given parameter [val…