我正在尝试打印一个程序,打印所有可能产生的回文,重新排列涉及一个字符以最大1个索引改变其位置,这意味着只允许相邻字符的交换。
我尝试了很多代码,但最好的代码是下一代。
只有我可以重新安排所有可能的回文,但所有的改变(不仅仅是一个)
CODE
#include <bits/stdc++.h>
using namespace std;
#define M 26
bool caNformPalindrome(string str, int* count_array)
{
//Initialize array with zeroes
for (int i = 0; i < 26; ++i)
{
count_array[i] = 0;
}
int length = str.length();
/* Updating frequency according to given string */
for (int i = 0; i < length; i++)
{
count_array[str[i] - 'a']++;
}
int odd_count = 0;
//Find odd_count
for (int i = 0; i < M; i++)
{
if (count_array[i] % 2 == 1)
{
odd_count++;
}
}
//if length is odd_count then only one letter's frequency must be odd_count
if ((length % 2 == 1 && odd_count == 1 ) || (length %2 == 0 && odd_count == 0))
{
return true;
}
else//if length is even no letter should have odd_count frequency
{
return false;
}
}
//Function to reverse the string
string reverse(string str)
{
string rev = str;
reverse(rev.begin(), rev.end());
return rev;
}
//Function to print
void printPalIndromes(string str)
{
int count_array[M];
// checking whether letter can make palindrome or not
if (!caNformPalindrome(str, count_array))
{
return;
}
int length = str.length();
// half will contain half part of all palindromes,
// that is why pushing half count_array of each letter
string half = "";
char mid;//store odd count charcter
for (int i = 0; i < M; i++)
{
if(count_array[i] % 2 == 1)
{
mid = i + 'a';
}
half += string(count_array[i] / 2, i + 'a');
}
string palindrome_string;
do
{
palindrome_string = half;
if (length % 2 == 1)
{
palindrome_string += mid;
}
palindrome_string += reverse(half);
cout<<palindrome_string<<endl;
}
while (next_permutation(half.begin(), half.end()));
}
//Main function
int main()
{
string str = "aabbc";
cout<<"Possible Permutations for Input_string only with 1 change"<<str<<" are: "<<endl;
printPalIndromes(str);
return 0;
}