Check if a given string is a rotation of a palindrome in C++


Here we will see, one string is palindrome after certain rotation or not. A palindrome is a string that is the same in both directions. A string rotation is a palindrome if that is like AAAAD. this is not a palindrome directly, but its rotation AADAA is a palindrome.

To check a string is rotated palindrome or not, then we will check this is a palindrome or not at the first time, after that, rotate it by one character, then check again, this checking will be performed n amount of time, where n is the number of characters.

Example

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindromeRange(string str, int left, int right){
   return (left >= right) || (str[left] == str[right] && isPalindromeRange(str, left + 1, right - 1));
}
bool isRotatedPalindrome(string str){
   int len = str.length();
   for (int i = 0; i < len; i++){
      rotate(str.begin(), str.begin() + 1, str.end());
      if (isPalindromeRange(str, 0, len - 1)) //if rotated string is palindrome, then return true
         return true;
   }
   return false;
}
int main(){
   string str = "AAAAD"; //AADAA is palindrome
   //rotate(str.begin(), str.begin() + 2, str.end());
   if (isRotatedPalindrome(str))
      cout << "Its rotation is palindrome";
   else
      cout << "Its rotation is not palindrome";
}

Output

Its rotation is palindrome

Updated on: 21-Oct-2019

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements