一道很好的综合题,考了回文处理,排列运算。
常看常新,注意自己犯得错误。
public class Solution {
public List<String> generatePalindromes(String s) {
List<String> result = new LinkedList<>();
if (s == null || s.length() == 0) {
return result;
}
Map<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 oddCount = 0;
//Character oddChar = '\0';
Character oddChar = null;
for (Map.Entry<Character, Integer> entry: map.entrySet()) {
if ((entry.getValue() & 1 ) == 1) {
if (++oddCount > 1) {
return result;
}
oddChar = entry.getKey();
entry.setValue(entry.getValue() - 1);
}
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<Character, Integer> entry: map.entrySet()) {
int count = entry.getValue() >> 1;
for (int i = 0; i < count; i++) {
sb.append(entry.getKey());
}
}
char[] carray = sb.toString().toCharArray();
List<StringBuilder> sbResult = new LinkedList<>();
helper(sbResult, new StringBuilder(), new boolean[carray.length], carray);
for (StringBuilder str: sbResult) {
//StringBuilder sbuilder = str.reverse();
if (oddChar != null)
result.add(str.toString() + oddChar + str.reverse().toString());
else
result.add(str.toString() + str.reverse().toString());
}
return result;
}
private void helper(List<StringBuilder> result, StringBuilder sb, boolean[] visited, char[] carray) {
if (sb.length() == carray.length) {
result.add(new StringBuilder(sb.toString()));
return;
}
for (int i = 0; i < carray.length; i++) {
if (visited[i]||(i > 0 && carray[i - 1] == carray[i] && !visited[i - 1])) {
continue;
}
sb.append(carray[i]);
visited[i] = true;
helper(result, sb, visited, carray);
visited[i] = false;
///sb.deleteCharAt(carray[i]);
sb.deleteCharAt(sb.length() - 1);
}
}
}
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 []
.
Show Similar Problems