Count special palindromes in a String in C++


We are given a string str. The goal is to count all substrings of str that are special palindromes and have length greater than 1. The special palindromes are strings that have either all the same characters or only the middle character as different. For example if string is “baabaa” then special palindromes that are substring of original are “aa”, “aabaa”, “aba”, “aa”

Let us understand with examples.

Input − str=”abccdcdf”

Output − Count of special palindromes in a String is − 3

Explanation − Substrings that are special palindromes are − “cc”, “cdc”, “dcd”

Input − str=”baabaab”

Output − Count of special palindromes in a String is − 4

Explanation − Substrings that are special palindromes are − “aa”, “aabaa”, “aba”, “aa”

The approach used in the below program is as follows

  • Create a string of alphabets and calculate its length. Pass the data to the function for further processing.

  • Declare a temporary variables count and i and set them to 0

  • Create an array of size of a string and initialize it with 0.

  • Start WHILE till i less than the length of a string

  • Inside the while, set a variable as total to 1 and a variable j to i + 1

  • Start another WHILE till str[i] = str[j] AND j less than length of a string

  • Inside the while, increment the total by 1 and j by 1

  • Set the count as count + ( total * (total + 1) / 2, arr[i] to total and i to j

  • Start loop FOR from j to 1 till the length of a string

  • Check if str[j] = str[j-1] then set arr[j] to arr[j-1]

  • Set a variable temp to str[j-1] and check if j > 0 AND j < one less the length of a string AND temp = str[j+1] AND sr[j]!=temp then set count as count + min(arr[j-1], arr[j+1])

  • Set the count a count - length of a string

  • Return the count

  • Print the result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int count_palindromes(string str, int len){
   int count = 0, i = 0;
   int arr[len] = { 0 };
   while (i < len){
      int total = 1;
      int j = i + 1;
      while (str[i] == str[j] && j < len){
         total++;
         j++;
      }
      count += (total * (total + 1) / 2);
      arr[i] = total;
      i = j;
   }
   for (int j = 1; j < len; j++){
      if (str[j] == str[j - 1]){
         arr[j] = arr[j - 1];
      }
      int temp = str[j - 1];
      if (j > 0 && j < (len - 1) && (temp == str[j + 1] && str[j] != temp)){
         count += min(arr[j-1], arr[j+1]);
      }
   }
   count = count - len;
   return count;
}
int main(){
   string str = "bcbaba";
   int len = str.length();
   cout<<"Count of special palindromes in a String are: "<< count_palindromes(str, len);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of special palindromes in a String are: 3

Updated on: 01-Dec-2020

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements