Coders Packet

Count the number of Palindromic Substrings in a String using C++

By Shravya Chinta

This is a packet that counts the number of Palindromic Substrings in a string using C++. A string or a number is said to be a Palindrome if it reads the same forwards and backward.

A C++ Program that returns the number of Palindromic Substrings in a given string. 

Examples: 

1) Input: "hiuj"

    Output: 4

    "h", "i", "u", "j" are the 4 Palindromic Substrings.

     Here, "hi", "uj", "iu" are also substrings however they're not Palindromes.

2) Input: "qqq"

    Output: 6

    "q", "q", "q", "qq", "qq", "qqq" are the 6 Palindromic Substrings.

3) Input: "xxp"

    Output: 4

    "x", "x", "xx", "p" are the 4 Palindromic Substrings.

Algorithm:

1) Input a string. Declare a counter 'res' that stores the no. of Palindromic Substrings and initialize it to zero.

2) Write 2 functions, one that counts the no. of Palindromic Substrings('countSubstrings') and the other that checks if a string is a Palindrome('palindrome').

2) In the 'countSubstrings' function, we iterate through the string using a 'for' loop.

3) Generate all the substrings by using substr() function.

4) If the substring is a Palindrome, we increase the counter by 1. 

5) Return the counter after iterating the entire string.

 

Download Complete Code

Comments

No comments yet