import
java.util.*;
public
class
GFG {
public
static
boolean
isPalin(String s,
HashMap<Character, Integer> freq) {
freq.clear();
for
(
int
i =
0
; i <
26
; i++) {
freq.put((
char
)(
'a'
+ i),
0
);
}
int
l = s.length();
for
(
int
i =
0
; i < l; i++) {
freq.put(s.charAt(i), freq.get(s.charAt(i)) +
1
);
}
int
odd =
0
;
for
(
int
i =
0
; i <
26
; i++) {
if
(freq.get((
char
)(
'a'
+ i)) %
2
==
1
) {
odd +=
1
;
}
}
return
(l %
2
==
1
&& odd ==
1
)
|| (l %
2
==
0
&& odd ==
0
);
}
public
static
String reverse(String s) {
char
[] arr = s.toCharArray();
StringBuilder sb =
new
StringBuilder();
for
(
int
i = arr.length -
1
; i >=
0
; i--) {
sb.append(arr[i]);
}
return
sb.toString();
}
public
static
void
printAllPossiblePalindromes(String s) {
HashMap<Character, Integer> freq
=
new
HashMap<Character, Integer>();
if
(!isPalin(s, freq)) {
return
;
}
int
l = s.length();
String half =
""
;
char
oddC =
'\0'
;
for
(
int
i =
0
; i <
26
; i++) {
if
(freq.get((
char
)(
'a'
+ i)) %
2
==
1
) {
oddC = (
char
)(
'a'
+ i);
}
half +=
new
String(
new
char
[(
int
)(freq.get((
char
)(
'a'
+ i)) /
2
)])
.replace(
'\0'
, (
char
)(
'a'
+ i));
}
String palin =
""
;
HashSet<String> xd =
new
HashSet<String>();
for
(
char
[] p : permute(half.toCharArray())) {
palin =
new
String(p);
if
(l %
2
==
1
) {
palin += oddC;
}
palin += reverse(
new
String(p));
if
(!xd.contains(palin)) {
System.out.println(palin);
xd.add(palin);
}
}
}
public
static
List<
char
[]> permute(
char
[] arr) {
List<
char
[]> result =
new
ArrayList<
char
[]>();
if
(arr.length ==
1
) {
result.add(arr);
}
else
{
for
(
int
i =
0
; i < arr.length; i++) {
char
current = arr[i];
char
[] remaining =
new
char
[arr.length -
1
];
int
index =
0
;
for
(
int
j =
0
; j < arr.length; j++) {
if
(j != i) {
remaining[index++] = arr[j];
}
}
List<
char
[]> remainingPermuted = permute(remaining);
for
(
int
j =
0
; j < remainingPermuted.size(); j++) {
char
[] temp =
new
char
[
1
+ remainingPermuted.get(j).length];
temp[
0
] = current;
for
(
int
k =
0
; k < remainingPermuted.get(j).length; k++) {
temp[k +
1
] = remainingPermuted.get(j)[k];
}
result.add(temp);
}
}
}
return
result;
}
public
static
void
main(String[] args) {
String s =
"aabbcadad"
;
System.out.println(
"All palindrome permutations of "
+ s);
printAllPossiblePalindromes(s);
}
}