檢查給定字串是否為 C++ 中的迴文旋轉


在這裡,我們將看到一個字串在某個旋轉後是否是迴文。迴文是一種在兩個方向都相同的字串。字串旋轉是一個迴文,如果它像 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)) //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";
}

輸出

Its rotation is palindrome

更新於:21-Oct-2019

240 次檢視

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告