
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Count all palindrome which is square of a palindrome in C++
- Count pairs of non-overlapping palindromic sub-strings of the given string in C++
- Count of sub-strings of length n possible from the given string in C++
- Find all distinct palindromic sub-strings of a given String in Python
- Find all palindromic sub-strings of a given string - Set 2 in Python
- Print all palindrome permutations of a string in C++
- Maximum even length sub-string that is permutation of a palindrome in C++
- Count of non-overlapping sub-strings “101” and “010” in the given binary string
- Count of sub-strings that contain character X at least once in C++
- Construct K Palindrome Strings in C++
- Count of sub-strings that do not contain all the characters from the set {‘a’, ‘b’, ‘c’} at the same time in C++
- Count palindrome words in a sentence in C++
- Count all Palindromic Subsequence in a given String in C++
- Count all sub-sequences having product
- Check if a string contains a sub-string in C++

Advertisements