LeetCode Palindrome Permutation II

原题链接在这里:https://leetcode.com/problems/palindrome-permutation-ii/

题目:

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 [].

题解:

与Palindrome Permutation相似.

先判断是否palindrome, 若不是返回空的res. 若是,先判断是否有一个奇数位,若有,改char放中间. 然后两遍分别加.

Time Complexity: O(2^n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public List<String> generatePalindromes(String s) {
 3         List<String> res = new ArrayList<String>();
 4         int [] map = new int[256];
 5         for(int i = 0; i<s.length(); i++){
 6             map[s.charAt(i)]++;
 7         }
 8         int count = 0;
 9         int po = 0;
10         for(int i = 0; i<256; i++){
11             if(count == 0 && map[i]%2 == 1){
12                 count++;
13                 po = i;
14             }else if(map[i]%2 == 1){
15                 return res;
16             }
17         }
18         
19         String cur = "";
20         if(po != 0){
21             map[po]--;
22             cur = "" + (char)po;
23         }
24         DFS(map, s.length(), cur, res);
25         return res;
26     }
27     
28     private void DFS(int [] map, int len, String cur, List<String> res){
29         if(cur.length() == len){
30             res.add(new String(cur));
31             return;
32         }
33         for(int i = 0; i<map.length; i++){
34             if(map[i] <= 0){
35                 continue;
36             }
37             map[i] -= 2;
38             cur = (char)i + cur + (char)i;
39             DFS(map, len, cur, res);
40             cur = cur.substring(1, cur.length()-1);
41             map[i] += 2;
42         }
43     }
44 }

 

你可能感兴趣的:(LeetCode Palindrome Permutation II)