Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create recursion #442

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions recursion
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// Expand in both directions of `low` and `high` to find
// palindrome of length `k`
bool expand(string str, int low, int high, int k)
{
// run till `str[low.high]` is not a palindrome
while (low >= 0 && high < str.length() && (str[low] == str[high]))
{
// return true palindrome of length `k` is found
if (high - low + 1 == k) {
return true;
}

// Expand in both directions
low--, high++;
}

// return false if palindrome of length `k` is not found
return false;
}

// Function to check if a palindromic substring of length `k` exists or not
bool longestPalindromicSubstring(string str, int k)
{
for (int i = 0; i < str.length() - 1; i++)
{
// check if odd or even length palindrome of length `k` exists,
// which have `str[i]` as its midpoint
if (expand(str, i, i, k) || expand(str, i, i + 1, k)) {
return true;
}
}

return false;
}

// Function to check if a given string is a rotated palindrome or not
bool isRotatedPalindrome(string str)
{
// length of the given string
int n = str.length();

// return true if the longest palindromic substring of length `n`
// exists in the string `str + str`
return longestPalindromicSubstring(str + str, n);
}

int main()
{
// palindromic string
string str = "ABCCBA";

// rotate it by 2 units
rotate(str.begin(), str.begin() + 2, str.end());

if (isRotatedPalindrome(str)) {
cout << "The string is a rotated palindrome";
}
else {
cout << "The string is not a rotated palindrome";
}

return 0;
}