-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathPalindromePermutationII267.java
64 lines (58 loc) · 1.55 KB
/
PalindromePermutationII267.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Given a string s, return all the palindromic permutations
* (without duplicates) of it. Return an empty list if no palindromic
* permutation could be form.
*
* Example 1:
* Input: "aabb"
* Output: ["abba", "baab"]
*
* Example 2:
* Input: "abc"
* Output: []
*/
public class PalindromePermutationII267 {
public List<String> generatePalindromes(String s) {
List<String> res = new ArrayList<>();
int[] map = new int[256];
int N = 0;
for (char ch: s.toCharArray()) {
map[ch]++;
N++;
}
StringBuilder sb = new StringBuilder();
int odd = -1;
for (int i=0; i<256; i++) {
if (map[i] % 2 != 0) {
if (odd != -1) return res;
odd = i;
sb.append((char) i);
map[i]--;
}
}
helper(map, 0, sb, res, N);
return res;
}
private void helper(int[] map, int curr, StringBuilder sb, List<String> res, int N) {
if (sb.length() == N) {
res.add(sb.toString());
return;
}
for (int i=0; i<256; i++) {
if (map[i] == 0) continue;
map[i] -= 2;
add(sb, (char) i);
helper(map, curr+1, sb, res, N);
remove(sb);
map[i] += 2;
}
}
private void add(StringBuilder sb, char ch) {
sb.append(ch);
sb.insert(0, ch);
}
private void remove(StringBuilder sb) {
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length()-1);
}
}