检查给定的字符串是否是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 妈妈生日祝福语简短励志