Count All Palindrome Sub-Strings in a String | Set 2 - GeeksforGeeks

06 Apr, 2022
Given a string, the task is to count all palindrome substring in a given string. Length of palindrome substring is greater then or equal to 2.
Examples:
Input : str = "abaab"
Output: 3
Explanation : 
All palindrome substring are :
 "aba", "aa", "baab" 

Input : str = "abbaeae"
Output: 4
Explanation : 
All palindrome substring are : 
"bb", "abba", "aea", "eae":
We have discussed a dynamic programming based solution in below post. Count All Palindrome Sub-Strings in a String | Set 1 The solution discussed here is extension of Longest Palindromic Substring problem. The idea is for each character in the given input string, we consider it as midpoint of a palindrome and expand it in both directions to find all palindromes of even and odd lengths. We use hashmap to keep track of all the distinct palindromes of length greater than 1 and return map size which have count of all possible palindrome substrings. The C++ implementation is given below. 
CPP
Java
C#
Javascript
// C++ program to count all distinct palindromic// substrings of a string.#include <bits/stdc++.h>using namespace std; // Returns total number of palindrome substring of// length greater than equal to 2int countPalindromes(string s){    unordered_map<string, int> m;    for (int i = 0; i < s.length(); i++) {         // check for odd length palindromes        for (int j = 0; j <= i; j++) {             if (!s[i + j])                break;             if (s[i - j] == s[i + j]) {                 // check for palindromes of length                // greater than 1                if ((i + j + 1) - (i - j) > 1)                    m[s.substr(i - j,                        (i + j + 1) - (i - j))]++;             } else                break;        }         // check for even length palindromes        for (int j = 0; j <= i; j++) {            if (!s[i + j + 1])                break;            if (s[i - j] == s[i + j + 1]) {                 // check for palindromes of length                // greater than 1                if ((i + j + 2) - (i - j) > 1)                    m[s.substr(i - j,                         (i + j + 2) - (i - j))]++;             } else                break;        }    }    return m.size();} // Driver codeint main(){    string s = "abbaeae";    cout << countPalindromes(s) << endl;    return 0;}
// Java Program to count palindrome substring// in a stringpublic class PalindromeSubstring {         // Method which return count palindrome substring    static int countPS(String str){        String temp = "";        StringBuffer stf;        int count = 0;        // Iterate the loop twice        for (int i = 0; i < str.length(); i++) {            for (int j = i + 1; j <= str.length(); j++) {                // Get each substring                temp = str.substring(i, j);                                 // If length is greater than or equal to two                // Check for palindrome                   if (temp.length() >= 2) {                    // Use StringBuffer class to reverse the string                    stf = new StringBuffer(temp);                    stf.reverse();                    // Compare substring with reverse of substring                    if (stf.toString().compareTo(temp) == 0)                        count++;                }            }        }        // return the count        return count;    }         // Driver Code    public static void main(String args[]) throws Exception {        // Declare and initialize the string        String str = "abbaeae";        // Call the method        System.out.println(countPS(str));    }} // This code is contributes by hungundji
// C# Program to count palindrome substring// in a stringusing System; class GFG{         // Method which return count palindrome substring    static int countPS(String str)    {        String temp = "";        String stf;        int count = 0;                 // Iterate the loop twice        for (int i = 0; i < str.Length; i++)        {            for (int j = i + 1;                     j <= str.Length; j++)            {                // Get each substring                temp = str.Substring(i, j-i);                                 // If length is greater than or equal to two                // Check for palindrome                if (temp.Length >= 2)                {                    // Use StringBuffer class to reverse                    // the string                    stf = temp;                    stf = reverse(temp);                                         // Compare substring with reverse of substring                    if (stf.ToString().CompareTo(temp) == 0)                        count++;                }            }        }                 // return the count        return count;    }         static String reverse(String input)    {        char[] a = input.ToCharArray();        int l, r = 0;        r = a.Length - 1;         for (l = 0; l < r; l++, r--)        {            // Swap values of l and r            char temp = a[l];            a[l] = a[r];            a[r] = temp;        }        return String.Join("",a);    }         // Driver Code    public static void Main(String []args)    {        // Declare and initialize the string        String str = "abbaeae";                 // Call the method        Console.WriteLine(countPS(str));    }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to count all distinct palindromic// substrings of a string. // Returns total number of palindrome substring of// length greater than equal to 2function countPalindromes(s){    let m = new Map();    for (let i = 0; i < s.length; i++) {         // check for odd length palindromes        for (let j = 0; j <= i; j++) {             if (!s[i + j])                break;             if (s[i - j] == s[i + j]) {                 // check for palindromes of length                // greater than 1                if ((i + j + 1) - (i - j) > 1){                    if(m.has(s.substr(i - j,(i + j + 1) - (i - j)))){                        m.set(s.substr(i - j,(i + j + 1) - (i - j)),m.get(s.substr(i - j,(i + j + 1) - (i - j))) + 1)                    }                    else m.set(s.substr(i - j,(i + j + 1) - (i - j)),1)                }             } else                break;        }         // check for even length palindromes        for (let j = 0; j <= i; j++) {            if (!s[i + j + 1])                break;            if (s[i - j] == s[i + j + 1]) {                 // check for palindromes of length                // greater than 1                if ((i + j + 2) - (i - j) > 1){                    if(m.has(s.substr(i - j,(i + j + 2) - (i - j)))){                        m.set(s.substr(i - j,(i + j + 2) - (i - j)),m.get(s.substr(i - j,(i + j + 2) - (i - j))) + 1)                    }                    else m.set(s.substr(i - j,(i + j + 2) - (i - j)),1)                }             } else                break;        }    }    return m.size;} // Driver code let s = "abbaeae"document.write(countPalindromes(s),"</br>") // This code is contributed by shinjanpatra </script>
4
Time complexity O(n2) Auxiliary Space O(n) This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
bilal-hungund
Rajput-Ji
sumitgumber28
shinjanpatra
cpp-unordered_map
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other