用 C++ 统计给定字符串中所有回文子序列
在本文档中,我们将讨论一个用于找出给定字符串中所有回文子序列数的程序。
为此,我们将获得一个字符串。我们的任务是找出可以在给定字符串中生成的回文子序列数。
示例
#include<iostream> #include<cstring> using namespace std; //returning total palindromic sequence int count_palin(string str){ int N = str.length(); //creating a 2D array int cps[N+1][N+1]; memset(cps, 0 ,sizeof(cps)); for (int i=0; i<N; i++) cps[i][i] = 1; for (int L=2; L<=N; L++){ for (int i=0; i<N; i++){ int k = L+i-1; if (str[i] == str[k]) cps[i][k] = cps[i][k-1] + cps[i+1][k] + 1; else cps[i][k] = cps[i][k-1] + cps[i+1][k] - cps[i+1][k-1]; } } return cps[0][N-1]; } int main(){ string str = "abcb"; cout << "Total palindromic subsequence are : " << count_palin(str) << endl; return 0; }
输出
Total palindromic subsequence are : 6
广告