Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
For example:
Given s = "aabb", return ["abba", "baab"].
Given s = "abc", return [].
Hint:
- If a palindromic permutation exists, we just need to generate the first half of the string.
- To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.
Solution:
First Compute the occurence and the middle of the
palindrome.
Then get the first half of the
palindrome by dfs.
Use the first half to generate the full palindrome.
public class Solution {
public List<String> generatePalindromes(String s) {
int[] count = new int[128];
for(char c : s.toCharArray()){
count[c] += 1;
}
String middle = "";
for(int i = 0 ; i < 128; i++){
if((count[i] & 1) != 0){
if(middle.length() > 0) return new ArrayList<String>();
else middle = "" + (char) i;
}
count[i] >>= 1;
}
List<String> ret = new ArrayList<String>();
helper(ret,new StringBuilder(),count,s.length() / 2);
for(int i = 0; i < ret.size(); i++){
ret.set(i ,ret.get(i) + middle + new StringBuilder(ret.get(i)).reverse().toString());
}
return ret;
}
public void helper(List<String> ret, StringBuilder path, int[] count, int len){
if(len == 0){
ret.add(path.toString());
return ;
}
for(int i = 0 ; i < count.length; i++){
if(count[i] > 0){
path.append((char) i);
count[i] -= 1;
helper(ret,path,count,len - 1);
count[i] += 1;
path.deleteCharAt(path.length() - 1);
}
}
}
}
本文介绍了一种生成字符串所有可能的回文排列的方法,并提供了一个详细的Java实现案例。通过计算字符出现次数来确定中间字符及半回文串,利用递归深度优先搜索(DFS)生成半回文串的所有唯一排列。
310

被折叠的 条评论
为什么被折叠?



