原文:

给定一根大小为 n 的绳子绳子。问题是按字母顺序打印的所有回文排列,如果可能的话打印“-1”。 举例:

input : str = "aabb"
output :
abba
baab
input : malayalam
output :
aalmymlaa
aamlylmaa
alamymala
almayamla
amalylama
amlayalma
laamymaal
lamayamal
lmaayaaml
maalylaam
malayalam
mlaayaalm

先决条件:进场:以下为步骤:

  1. 如果可能,使用字符串的字符找到,否则打印“-1”并返回。
  2. 如果从词典学的角度来看,第一个回文字符串被获得,那么打印它。
  3. 现在,使用字符串的相同字符集找到下一个更高的回文字符串。参考帖子。 这两个帖子唯一的区别是,一个数字在排列,另一个小写字母在排列。
  4. 如果获得下一个更高的回文字符串,则打印它并转到步骤 3,否则返回。

请注意,字符串字符串总是被操纵,以便使用上述步骤获得回文字符串。

c

// c   implementation to print all the palindromic
// permutations alphabetically
#include 
using namespace std;
const char max_char = 26;
// function to count frequency of each char in the
// string. freq[0] for 'a', ...., freq[25] for 'z'
void countfreq(char str[], int freq[], int n)
{
    for (int i = 0; i < n; i  )
        freq[str[i] - 'a']  ;
}
// cases to check whether a palindromic
// string can be formed or not
bool canmakepalindrome(int freq[], int n)
{
    // count_odd to count no of
    // chars with odd frequency
    int count_odd = 0;
    for (int i = 0; i < max_char; i  )
        if (freq[i] % 2 != 0)
            count_odd  ;
    // for even length string
    // no odd freq character
    if (n % 2 == 0) {
        if (count_odd > 0)
            return false;
        else
            return true;
    }
    // for odd length string
    // one odd freq character
    if (count_odd != 1)
        return false;
    return true;
}
// function to find odd freq char and reducing its
// freq by 1, returns garbage value if odd freq
// char is not present
char findoddandremoveitsfreq(int freq[])
{
    char odd_char;
    for (int i = 0; i < max_char; i  ) {
        if (freq[i] % 2 != 0) {
            freq[i]--;
            odd_char = (char)(i   'a');
            break;
        }
    }
    return odd_char;
}
// to find lexicographically first palindromic
// string.
bool findpalindromicstring(char str[], int n)
{
    int freq[max_char] = { 0 };
    countfreq(str, freq, n);
    // check whether a palindromic string
    // can be formed or not with the
    // characters of 'str'
    if (!canmakepalindrome(freq, n))
        // cannot be formed
        return false;
    // assigning odd freq character if present
    // else some garbage value
    char odd_char = findoddandremoveitsfreq(freq);
    // indexes to store characters from the front
    // and end
    int front_index = 0, rear_index = n - 1;
    // traverse characters in alphabetical order
    for (int i = 0; i < max_char; i  ) {
        if (freq[i] != 0) {
            char ch = (char)(i   'a');
            // store 'ch' to half its frequency times
            // from the front and rear end. note that
            // odd character is removed by
            // findoddandremoveitsfreq()
            for (int j = 1; j <= freq[i] / 2; j  ) {
                str[front_index  ] = ch;
                str[rear_index--] = ch;
            }
        }
    }
    // if true then odd frequency char exists
    // store it to its corresponding index
    if (front_index == rear_index)
        str[front_index] = odd_char;
    // palindromic string can be formed
    return true;
}
// function to reverse the characters in the
// range i to j in 'str'
void reverse(char str[], int i, int j)
{
    while (i < j) {
        swap(str[i], str[j]);
        i  ;
        j--;
    }
}
// function to find next higher palindromic
// string using the same set of characters
bool nextpalin(char str[], int n)
{
    // if length of 'str' is less than '3'
    // then no higher palindromic string
    // can be formed
    if (n <= 3)
        return false;
    // find the index of last character
    // in the 1st half of 'str'
    int mid = n / 2 - 1;
    int i, j;
    // start from the (mid-1)th character and
    // find the first character that is
    // alphabetically smaller than the
    // character next to it.
    for (i = mid - 1; i >= 0; i--)
        if (str[i] < str[i   1])
            break;
    // if no such character is found, then all characters
    // are in descending order (alphabetically) which
    // means there cannot be a higher palindromic string
    // with same set of characters
    if (i < 0)
        return false;
    // find the alphabetically smallest character on
    // right side of ith character which is greater
    // than str[i] up to index 'mid'
    int smallest = i   1;
    for (j = i   2; j <= mid; j  )
        if (str[j] > str[i] && str[j] < str[smallest])
            smallest = j;
    // swap str[i] with str[smallest]
    swap(str[i], str[smallest]);
    // as the string is a palindrome, the same
    // swap of characters should be performed
    // in the 2nd half of 'str'
    swap(str[n - i - 1], str[n - smallest - 1]);
    // reverse characters in the range (i 1) to mid
    reverse(str, i   1, mid);
    // if n is even, then reverse characters in the
    // range mid 1 to n-i-2
    if (n % 2 == 0)
        reverse(str, mid   1, n - i - 2);
    // else if n is odd, then reverse characters
    // in the range mid 2 to n-i-2
    else
        reverse(str, mid   2, n - i - 2);
    // next alphabetically higher palindromic
    // string can be formed
    return true;
}
// function to print all the palindromic permutations
// alphabetically
void printallpalinpermutations(char str[], int n)
{
    // check if lexicographically first palindromic string
    // can be formed or not using the characters of 'str'
    if (!(findpalindromicstring(str, n))) {
        // cannot be formed
        cout << "-1";
        return;
    }
    // print all palindromic permutations
    do {
        cout << str << endl;
    } while (nextpalin(str, n));
}
// driver program to test above
int main()
{
    char str[] = "malayalam";
    int n = strlen(str);
    printallpalinpermutations(str, n);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java code to print all the
// palindromic permutations alphabetically
import java.util.*;
class gfg {
static int max_char = 26;
// function to count frequency
// of each char in the string.
// freq[0] for 'a', ...., freq[25] for 'z'
static void countfreq(char str[],
                    int freq[], int n){
    for (int i = 0; i < n; i  )
        freq[str[i] - 'a']  ;
}
// cases to check whether a palindromic
// string can be formed or not
static boolean canmakepalindrome
            (int freq[], int n){
    // count_odd to count no of
    // chars with odd frequency
    int count_odd = 0;
    for (int i = 0; i < max_char; i  )
        if (freq[i] % 2 != 0)
            count_odd  ;
    // for even length string
    // no odd freq character
    if (n % 2 == 0) {
        if (count_odd > 0)
            return false;
        else
            return true;
    }
    // for odd length string
    // one odd freq character
    if (count_odd != 1)
        return false;
    return true;
}
// function for odd freq char and
// reducing its freq by 1, returns
// garbage value if odd freq
// char is not present
static char findoddandremoveitsfreq
                    (int freq[])
{
    char odd_char = 'a';
    for (int i = 0; i < max_char; i  )
    {
        if (freq[i] % 2 != 0) {
            freq[i]--;
            odd_char = (char)(i   'a');
            break;
        }
    }
    return odd_char;
}
// to find lexicographically
// first palindromic string.
static boolean findpalindromicstring
            (char[] str, int n)
{
    int[] freq = new int[max_char] ;
    countfreq(str, freq, n);
    // check whether a palindromic
    // string can be formed or not
    // with the characters of 'str'
    if (!canmakepalindrome(freq, n))
        return false;
    // assigning odd freq character if
    // present else some garbage value
    char odd_char =
        findoddandremoveitsfreq(freq);
    // indexes to store characters
    // from the front and end
    int front_index = 0,
        rear_index = n - 1;
    // traverse characters
    // in alphabetical order
    for (int i = 0; i < max_char; i  )
    {
        if (freq[i] != 0) {
            char ch = (char)(i   'a');
            // store 'ch' to half its frequency
            // times from the front and rear
            // end. note that odd character is
            // removed by findoddandremoveitsfreq()
            for (int j = 1; j <= freq[i] / 2; j  ){
                str[front_index  ] = ch;
                str[rear_index--] = ch;
            }
        }
    }
    // if true then odd frequency char exists
    // store it to its corresponding index
    if (front_index == rear_index)
        str[front_index] = odd_char;
    // palindromic string can be formed
    return true;
}
// function to reverse the characters
// in the range i to j in 'str'
static void reverse(char[] str, int i, int j)
{
    char temp;
    while (i < j) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i  ;
        j--;
    }
}
// function to find next higher
// palindromic string using the
// same set of characters
static boolean nextpalin(char[] str, int n)
{
    // if length of 'str' is less
    // than '3' then no higher
    // palindromic string can be formed
    if (n <= 3)
        return false;
    // find the index of last character
    // in the 1st half of 'str'
    int mid = n / 2 - 1;
    int i, j;
    // start from the (mid-1)th character
    // and find the first character
    // that is alphabetically smaller
    // than the character next to it.
    for (i = mid - 1; i >= 0; i--)
        if (str[i] < str[i   1])
            break;
    // if no such character is found,
    // then all characters are in
    // descending order (alphabetically)
    // which means there cannot be a
    // higher palindromic string
    // with same set of characters
    if (i < 0)
        return false;
    // find the alphabetically smallest
    // character on right side of ith
    // character which is greater than
    // str[i] up to index 'mid'
    int smallest = i   1;
    for (j = i   2; j <= mid; j  )
        if (str[j] > str[i] && str[j]
                     < str[smallest])
            smallest = j;
char temp;
    // swap str[i] with str[smallest]
    temp = str[i];
    str[i] = str[smallest];
    str[smallest] = temp;
    // as the string is a palindrome,
    // the same swap of characters
    // should be performed in the
    // 2nd half of 'str'
    temp = str[n - i - 1];
    str[n - i - 1] = str[n - smallest - 1];
    str[n - smallest - 1] = temp;
    // reverse characters in the
    // range (i 1) to mid
    reverse(str, i   1, mid);
    // if n is even, then reverse
    // characters in the range
    // mid 1 to n-i-2
    if (n % 2 == 0)
        reverse(str, mid   1, n - i - 2);
    // else if n is odd, then
    // reverse characters in
    // the range mid 2 to n-i-2
    else
        reverse(str, mid   2, n - i - 2);
    // next alphabetically higher
    // palindromic string can be formed
    return true;
}
// function to print all palindromic
// permutations alphabetically
static void printallpalinpermutations
            (char[] str, int n) {
    // check if lexicographically
    // first palindromic string can
    // be formed or not using the
    // characters of 'str'
    if (!(findpalindromicstring(str, n)))
    {
        // cannot be formed
        system.out.print("-1");
        return;
    }
    // print all palindromic permutations
    do {
        system.out.println(str);
    } while (nextpalin(str, n));
}
// driver program
public static void main(string[] args)
{
    char[] str = ("malayalam").tochararray();
    int n = str.length;
    printallpalinpermutations(str, n);
}
}
// this code is contributed by gitanjali.

python 3

# python3 implementation to print all the
# palindromic permutations alphabetically
# import library
import numpy as np
max_char = 26
# function to count frequency of each in the
# string. freq[0] for 'a', ...., freq[25] for 'z'
def countfreq(str, freq, n) :
    for i in range(0, n) :
        freq[ord(str[i]) - ord('a')]  = 1
# cases to check whether a palindromic
# string can be formed or not
def canmakepalindrome(freq, n) :
    # count_odd to count no of
    # s with odd frequency
    count_odd = 0
    for i in range(0, max_char) :
        if (freq[i] % 2 != 0):
            count_odd  = 1
    # for even length string
    # no odd freq character
    if (n % 2 == 0):
        if (count_odd > 0):
            return false
        else:
            return true
    # for odd length string
    # one odd freq character
    if (count_odd != 1):
        return false
    return true
# function to find odd freq and reducing
# its freq by 1, returns garbage
# value if odd freq is not present
def findoddandremoveitsfreq(freq) :
    odd_char = 0
    for i in range(0, max_char) :
        if (freq[i] % 2 != 0):
            freq[i] = freq[i] - 1
            odd_char = (chr)(i   ord('a'))
            break
    return odd_char
# to find lexicographically first
# palindromic string.
def findpalindromicstring(str, n) :
    freq = np.zeros(26, dtype = np.int)
    countfreq(str, freq, n)
    # check whether a palindromic string
    # can be formed or not with the
    # characters of 'str'
    if (not(canmakepalindrome(freq, n))):
        # cannot be formed
        return false
    # assigning odd freq character if
    # present else some garbage value
    odd_char = findoddandremoveitsfreq(freq)
    # indexes to store acters from
    # the front and end
    front_index = 0; rear_index = n - 1
    # traverse acters in alphabetical order
    for i in range(0, max_char) :
        if (freq[i] != 0) :
            ch = (chr)(i   ord('a'))
            # store 'ch' to half its frequency times
            # from the front and rear end. note that
            # odd character is removed by
            # findoddandremoveitsfreq()
            for j in range(1, int(freq[i]/2)   1):
                str[front_index] = ch
                front_index  = 1
                str[rear_index] = ch
                rear_index -= 1
    # if true then odd frequency exists
    # store it to its corresponding index
    if (front_index == rear_index):
        str[front_index] = odd_char
    # palindromic string can be formed
    return true
# function to reverse the acters in the
# range i to j in 'str'
def reverse( str, i, j):
    while (i < j):
        str[i], str[j] = str[j], str[i]
        i  = 1
        j -= 1
# function to find next higher palindromic
# string using the same set of acters
def nextpalin(str, n) :
    # if length of 'str' is less than '3'
    # then no higher palindromic string
    # can be formed
    if (n <= 3):
        return false
    # find the index of last acter
    # in the 1st half of 'str'
    mid = int (n / 2) - 1
    # start from the (mid-1)th acter and
    # find the first acter that is
    # alphabetically smaller than the
    # acter next to it
    i = mid -1
    while(i >= 0) :
        if (str[i] < str[i   1]):
            break
        i -= 1
    # if no such character is found, then
    # all characters are in descending order
    # (alphabetically) which means there cannot
    # be a higher palindromic string with same
    # set of characters
    if (i < 0):
        return false
    # find the alphabetically smallest character
    # on right side of ith character which is
    # greater than str[i] up to index 'mid'
    smallest = i   1;
    for j in range(i   2, mid   1):
        if (str[j] > str[i] and str[j] < str[smallest]):
            smallest = j
    # swap str[i] with str[smallest]
    str[i], str[smallest] = str[smallest], str[i]
    # as the string is a palindrome, the same
    # swap of characters should be performed
    # in the 2nd half of 'str'
    str[n - i - 1], str[n - smallest - 1] = str[n - smallest - 1], str[n - i - 1]
    # reverse characters in the range (i 1) to mid
    reverse(str, i   1, mid)
    # if n is even, then reverse characters in the
    # range mid 1 to n-i-2
    if (n % 2 == 0):
        reverse(str, mid   1, n - i - 2)
    # else if n is odd, then reverse acters
    # in the range mid 2 to n-i-2
    else:
        reverse(str, mid   2, n - i - 2)
    # next alphabetically higher palindromic
    # string can be formed
    return true
# function to print all the palindromic
# permutations alphabetically
def printallpalinpermutations(str, n) :
    # check if lexicographically first
    # palindromic string can be formed
    # or not using the acters of 'str'
    if (not(findpalindromicstring(str, n))):
           # cannot be formed
        print ("-1")
        return
    # converting list into string
    print ( "".join(str))
    # print all palindromic permutations
    while (nextpalin(str, n)):
        # converting list into string
        print ("".join(str))
# driver code
str= "malayalam"
n = len(str)
# convertnig string into list so that
# replacement of characters would be easy
str = list(str)
printallpalinpermutations(str, n)
# this article is contributed by 'saloni1297'

c

// c# code to print all the palindromic
// permutations alphabetically
using system;
class gfg {
static int max_char = 26;
// function to count frequency
// of each char in the string.
// freq[0] for 'a', ...., freq[25] for 'z'
static void countfreq(char []str, int []freq, int n)
{
    for (int i = 0; i < n; i  )
        freq[str[i] - 'a']  ;
}
// cases to check whether a palindromic
// string can be formed or not
static boolean canmakepalindrome(int []freq, int n)
{
    // count_odd to count no of
    // chars with odd frequency
    int count_odd = 0;
    for (int i = 0; i < max_char; i  )
        if (freq[i] % 2 != 0)
            count_odd  ;
    // for even length string
    // no odd freq character
    if (n % 2 == 0) {
        if (count_odd > 0)
            return false;
        else
            return true;
    }
    // for odd length string
    // one odd freq character
    if (count_odd != 1)
        return false;
    return true;
}
// function for odd freq char and
// reducing its freq by 1, returns
// garbage value if odd freq
// char is not present
static char findoddandremoveitsfreq(int []freq)
{
    char odd_char = 'a';
    for (int i = 0; i < max_char; i  )
    {
        if (freq[i] % 2 != 0) {
            freq[i]--;
            odd_char = (char)(i   'a');
            break;
        }
    }
    return odd_char;
}
// to find lexicographically
// first palindromic string.
static boolean findpalindromicstring(char[] str, int n)
{
    int[] freq = new int[max_char] ;
    countfreq(str, freq, n);
    // check whether a palindromic
    // string can be formed or not
    // with the characters of 'str'
    if (!canmakepalindrome(freq, n))
        return false;
    // assigning odd freq character if
    // present else some garbage value
    char odd_char =
        findoddandremoveitsfreq(freq);
    // indexes to store characters
    // from the front and end
    int front_index = 0,
        rear_index = n - 1;
    // traverse characters
    // in alphabetical order
    for (int i = 0; i < max_char; i  )
    {
        if (freq[i] != 0) {
            char ch = (char)(i   'a');
            // store 'ch' to half its frequency
            // times from the front and rear
            // end. note that odd character is
            // removed by findoddandremoveitsfreq()
            for (int j = 1; j <= freq[i] / 2; j  ){
                str[front_index  ] = ch;
                str[rear_index--] = ch;
            }
        }
    }
    // if true then odd frequency char exists
    // store it to its corresponding index
    if (front_index == rear_index)
        str[front_index] = odd_char;
    // palindromic string can be formed
    return true;
}
// function to reverse the characters
// in the range i to j in 'str'
static void reverse(char[] str, int i, int j)
{
    char temp;
    while (i < j) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i  ;
        j--;
    }
}
// function to find next higher
// palindromic string using the
// same set of characters
static boolean nextpalin(char[] str, int n)
{
    // if length of 'str' is less
    // than '3' then no higher
    // palindromic string can be formed
    if (n <= 3)
        return false;
    // find the index of last character
    // in the 1st half of 'str'
    int mid = n / 2 - 1;
    int i, j;
    // start from the (mid-1)th character
    // and find the first character
    // that is alphabetically smaller
    // than the character next to it.
    for (i = mid - 1; i >= 0; i--)
        if (str[i] < str[i   1])
            break;
    // if no such character is found,
    // then all characters are in
    // descending order (alphabetically)
    // which means there cannot be a
    // higher palindromic string
    // with same set of characters
    if (i < 0)
        return false;
    // find the alphabetically smallest
    // character on right side of ith
    // character which is greater than
    // str[i] up to index 'mid'
    int smallest = i   1;
    for (j = i   2; j <= mid; j  )
        if (str[j] > str[i] && str[j]
                    < str[smallest])
            smallest = j;
char temp;
    // swap str[i] with str[smallest]
    temp = str[i];
    str[i] = str[smallest];
    str[smallest] = temp;
    // as the string is a palindrome,
    // the same swap of characters
    // should be performed in the
    // 2nd half of 'str'
    temp = str[n - i - 1];
    str[n - i - 1] = str[n - smallest - 1];
    str[n - smallest - 1] = temp;
    // reverse characters in the
    // range (i 1) to mid
    reverse(str, i   1, mid);
    // if n is even, then reverse
    // characters in the range
    // mid 1 to n-i-2
    if (n % 2 == 0)
        reverse(str, mid   1, n - i - 2);
    // else if n is odd, then
    // reverse characters in
    // the range mid 2 to n-i-2
    else
        reverse(str, mid   2, n - i - 2);
    // next alphabetically higher
    // palindromic string can be formed
    return true;
}
// function to print all palindromic
// permutations alphabetically
static void printallpalinpermutations(char[] str, int n)
{
    // check if lexicographically
    // first palindromic string can
    // be formed or not using the
    // characters of 'str'
    if (!(findpalindromicstring(str, n)))
    {
        // cannot be formed
        console.writeline("-1");
        return;
    }
    // print all palindromic permutations
    do {
    console.writeline(str);
    } while (nextpalin(str, n));
}
// driver program
public static void main(string[] args)
{
    char[] str = ("malayalam").tochararray();
    int n = str.length;
    printallpalinpermutations(str, n);
}
}
// this code is contributed by parashar.

输出:

aalmymlaa
aamlylmaa
alamymala
almayamla
amalylama
amlayalma
laamymaal
lamayamal
lmaayaaml
maalylaam
malayalam
mlaayaalm

时间复杂度:o(mn),其中 m*的回文排列数。