1. 程式人生 > 實用技巧 >[LeetCode] 267. Palindrome Permutation II

[LeetCode] 267. Palindrome Permutation II

Given a strings, 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 題目總結