Given a strings
, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
class Solution {
public List<String> generatePalindromes(String s) {
List<String> res = new ArrayList<>();
if(s == null || s.length() == 0)
return res;
int[] count = new int[128];
for(int i = 0; i < s.length(); i++) {
count[s.charAt(i)]++;
}
int odd = 0;
for(int i = 0; i < count.length; i++) {
if(count[i] % 2 == 1) {
odd++;
if(odd > 1)
return res;
}
}
StringBuilder sb = new StringBuilder();
String c = "";
for(int i = 0; i < count.length; i++) {
if(count[i] % 2 == 0) {
for(int j = 0; j < count[i] / 2; j++)
sb.append((char) (i));
} else {
c = c + (char) i;
for(int j = 0; j < count[i] / 2; j++)
sb.append((char) (i));
}
}
char[] cs = sb.toString().toCharArray();
Arrays.sort(cs);
boolean[] visited = new boolean[cs.length];
helper(res, "", cs, c, visited);
return res;
}
public void helper(List<String> res, String curr, char[] cs, String odd, boolean[] visited) {
if(curr.length() == cs.length) {
StringBuilder sb = new StringBuilder(curr);
res.add(curr + odd + sb.reverse().toString());
return;
}
for(int i = 0; i < cs.length; i++) {
if(visited[i])
continue;
if(i > 0 && cs[i] == cs[i - 1] && !visited[i - 1])
continue;
visited[i] = true;
helper(res, curr + cs[i], cs, odd, visited);
visited[i] = false;
}
}
}