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.
感觉这类题做多了也就那么回事,只不过在dfs之前的条件需要仔细一些。
在判断是否是回文的时候考的绿naive了一点,用了int[] dict = new int[26], 结果发现输入不局限于a-z。还有就是统计奇数次的字符时,顺便需要更新可能作为中间点的字符。
代码:
public List<String> generatePalindromes(String s) {
HashMap<Character, Integer> map = new HashMap<>();
for(int i=0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i), map.get(s.charAt(i))+1);
}else{
map.put(s.charAt(i), 1);
}
}
int count = 0;
char single = '*';
List<Character> list = new ArrayList<>();
for(Map.Entry<Character, Integer> entry: map.entrySet()){
int value = entry.getValue();
char ch = entry.getKey();
if(value%2!= 0){
count++;
single = ch;
if(value>1){
for(int i=0;i<(value-1)/2;i++){
list.add(ch);
}
}
}else{
for(int i=0;i<value/2;i++){
list.add(ch);
}
}
}
if(count>1){
return new ArrayList<>();
}
boolean visited[] = new boolean[list.size()];
List<String> result = new ArrayList<>();
//generate premutations
String startStr = single == '*'?"":single+"";
int totalLen = single == '*'?2*list.size():2*list.size()+1;
generatePermutations(list, startStr, visited, result, totalLen);
return result;
}
private void generatePermutations(List<Character> characters, String curStr, boolean[]visited, List<String> result, int totalLen){
if(curStr.length() == totalLen){
result.add(curStr);
return;
}
for(int i=0;i<characters.size();i++){
if(i!=0 && characters.get(i) == characters.get(i-1) && visited[i-1] == false) continue;
if(visited[i] == false){
visited[i] = true;
char ch = (characters.get(i));
generatePermutations(characters, ch+curStr+ch, visited, result, totalLen);
visited[i] = false;
}else{
continue;
}
}
}