用 C++ 统计字符串中所有回文字串
在本教程中,我们将讨论一个程序,该程序用于查找字符串中回文字符串的数量。
为此,我们将给定一个字符串。我们的任务是统计给定字符串中长度大于 3 的回文字符串的数量。
示例
#include<bits/stdc++.h>
using namespace std;
//counting palindrome strings
int count_pstr(char str[], int n){
int dp[n][n];
memset(dp, 0, sizeof(dp));
bool P[n][n];
memset(P, false , sizeof(P));
for (int i= 0; i< n; i++)
P[i][i] = true;
for (int i=0; i<n-1; i++) {
if (str[i] == str[i+1]) {
P[i][i+1] = true;
dp[i][i+1] = 1 ;
}
}
for (int gap=2 ; gap<n; gap++) {
for (int i=0; i<n-gap; i++) {
int j = gap + i;
//if current string is palindrome
if (str[i] == str[j] && P[i+1][j-1] )
P[i][j] = true;
if (P[i][j] == true)
dp[i][j] = dp[i][j-1] + dp[i+1][j] + 1 - dp[i+1][j-1];
else
dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1];
}
}
return dp[0][n-1];
}
int main(){
char str[] = "abaab";
int n = strlen(str);
cout << count_pstr(str, n) << endl;
return 0;
}输出
3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP