Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all Palindrome Sub-Strings in a String in C++
In this tutorial, we will be discussing a program to find the number of palindrome sub strings in a string.
For this we will be given a string. Our task is to count the number of palindrome sub strings in the given string with length greater than 3.
Example
#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;
}
Output
3
Advertisements