检查给定的字符串是否是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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短