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

Example 1:

Input: "aabb"
Output: ["abba", "baab"]

Example 2:

Input: "abc"
Output: []

回文排列II。

给定一个字符串 s ,返回其通过重新排列组合后所有可能的回文字符串,并去除重复的组合。如不能形成任何回文排列时,则返回一个空列表。

思路是backtracking。对于一个input字符串而言,他自己不一定是回文,但是如果字符串里面只有至多一个字符的出现次数是奇数,其他字符的出现次数都是偶数,那么他的permutation就可以组成回文。所以我们首先统计一下input字符串里面各个字母的出现次数,如果统计结果不能满足回文的条件则返回一个空集res,否则我们就可以开始找可以组成的回文串。

我们先找一下,是否有出现过奇数次数的字母,如果有,则这个字母只能作为回文串中间的那个字母。之后就是用一个helper函数去做permutation。退出条件就是生成的字符串的长度和input字符串的长度一样,加入结果集。

时间 - ?

空间O(n)

Java实现

 1 class Solution {
 2     public List<String> generatePalindromes(String s) {
 3         List<String> res = new ArrayList<>();
 4         int[] map = new int[256];
 5         int odd = 0;
 6         for (char c : s.toCharArray()) {
 7             map[c]++;
 8             if (map[c] % 2 == 1) {
 9                 odd++;
10             } else {
11                 odd--;
12             }
13         }
14 
15         // corner case
16         if (s.length() == 0 || odd > 1) {
17             return res;
18         }
19         // normal case
20         String temp = "";
21         for (int i = 0; i < 256 && odd == 1; i++) {
22             if (map[i] % 2 == 1) {
23                 temp += (char) i;
24                 map[i]--;
25                 break;
26             }
27         }
28         helper(res, temp, map, s.length());
29         return res;
30     }
31 
32     private void helper(List<String> res, String temp, int[] map, int n) {
33         if (temp.length() == n) {
34             res.add(temp);
35             return;
36         }
37         for (int i = 0; i < 256; i++) {
38             if (map[i] > 0) {
39                 map[i] -= 2;
40                 helper(res, (char) i + temp + (char) i, map, n);
41                 map[i] += 2;
42             }
43         }
44     }
45 }

 

LeetCode 题目总结

posted @ 2020-11-13 12:11  CNoodle  阅读(195)  评论(0编辑  收藏  举报