Rotated Palindrome - C++ Solution

1. Introduction

The "Rotated Palindrome" problem is an intriguing challenge that combines concepts of string rotation and palindrome checking. This problem tests a developer's skills in string manipulation and understanding of how rotations can transform a string into a palindrome.

Problem

The task is to determine whether a given string is a rotated version of a palindrome. A palindrome is a string that reads the same forwards and backwards, and a rotated palindrome is a string that becomes a palindrome when rotated by some number of positions.

2. Solution Steps

1. Concatenate the string with itself to account for all possible rotations.

2. Iterate through each character of the concatenated string (up to the length of the original string).

3. Extract a substring of the original string's length starting from each character.

4. Check if this substring is a palindrome.

5. If any of the substrings is a palindrome, return true; otherwise, return false.

3. Code Program

#include <iostream>
#include <string>
using namespace std;

// Function to check if a string is a palindrome
bool isPalindrome(const string &str) {
    int left = 0, right = str.length() - 1;
    while (left < right) {
        if (str[left++] != str[right--]) {
            return false; // Not a palindrome
        }
    }
    return true; // Is a palindrome
}

// Function to check if the string is a rotated palindrome
bool isRotatedPalindrome(const string &str) {
    if (str.empty()) {
        return false; // Empty string is not a palindrome
    }

    string temp = str + str; // Concatenate the string with itself
    for (int i = 0; i < str.length(); i++) {
        // Check if substring of original length is a palindrome
        if (isPalindrome(temp.substr(i, str.length()))) {
            return true; // Rotated palindrome found
        }
    }
    return false; // No rotated palindrome found
}

int main() {
    string input = "CBAABCD";
    cout << boolalpha << isRotatedPalindrome(input) << endl;
    return 0;
}

Output:

true

Explanation:

The program first checks for palindromes in all rotations of the given string. It does this by concatenating the string with itself and then extracting substrings of the original length, starting from each character in the concatenated string. Each substring is checked to see if it is a palindrome. 

This approach ensures that all possible rotations are considered, efficiently determining if the string is a rotated palindrome.


Comments