在 C++ 中检查给定字符串是否为回文的旋转

c++server side programmingprogramming更新于 2024/9/23 0:56:00

在这里我们将看到,一个字符串经过一定的旋转后是否为回文。回文是在两个方向上相同的字符串。如果字符串旋转为 AAAAD,则该字符串为回文。这不是直接的回文,而是其旋转 AADAA 是回文。

要检查字符串是否为旋转回文,我们将首先检查它是否为回文,之后将其旋转一个字符,然后再次检查,此检查将执行 n 次,其中 n 是字符数。

示例

#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)) //如果旋转后的字符串是回文,则返回 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";
}

输出

Its rotation is palindrome

相关文章