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

Hint:

  1. If a palindromic permutation exists, we just need to generate the first half of the string.
  2. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.

266. Palindrome Permutation 的拓展,266只是判断全排列是否存在回文的,此题要返回所有的回文全排列。提示:如果回文全排列存在,只需要生成前半段字符串,后面的直接根据前半段得到。用Permutations II or Next Permutation的方法去生成不同的全排列。

Python:

class Solution(object):
def generatePalindromes(self, s):
"""
:type s: str
:rtype: List[str]
"""
cnt = collections.Counter(s)
mid = ''.join(k for k, v in cnt.iteritems() if v % 2)
chars = ''.join(k * (v / 2) for k, v in cnt.iteritems())
return self.permuteUnique(mid, chars) if len(mid) < 2 else [] def permuteUnique(self, mid, nums):
result = []
used = [False] * len(nums)
self.permuteUniqueRecu(mid, result, used, [], nums)
return result def permuteUniqueRecu(self, mid, result, used, cur, nums):
if len(cur) == len(nums):
half_palindrome = ''.join(cur)
result.append(half_palindrome + mid + half_palindrome[::-1])
return
for i in xrange(len(nums)):
if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]):
used[i] = True
cur.append(nums[i])
self.permuteUniqueRecu(mid, result, used, cur, nums)
cur.pop()
used[i] = False

Python:

class Solution2(object):
def generatePalindromes(self, s):
"""
:type s: str
:rtype: List[str]
"""
cnt = collections.Counter(s)
mid = tuple(k for k, v in cnt.iteritems() if v % 2)
chars = ''.join(k * (v / 2) for k, v in cnt.iteritems())
return [''.join(half_palindrome + mid + half_palindrome[::-1]) \
for half_palindrome in set(itertools.permutations(chars))] if len(mid) < 2 else []

C++:

class Solution {
public:
vector<string> generatePalindromes(string s) {
vector<string> res;
unordered_map<char, int> m;
string t = "", mid = "";
for (auto a : s) ++m[a];
for (auto it : m) {
if (it.second % 2 == 1) mid += it.first;
t += string(it.second / 2, it.first);
if (mid.size() > 1) return {};
}
permute(t, 0, mid, res);
return res;
}
void permute(string &t, int start, string mid, vector<string> &res) {
if (start >= t.size()) {
res.push_back(t + mid + string(t.rbegin(), t.rend()));
}
for (int i = start; i < t.size(); ++i) {
if (i != start && t[i] == t[start]) continue;
swap(t[i], t[start]);
permute(t, start + 1, mid, res);
swap(t[i], t[start]);
}
}
};

C++:

class Solution {
public:
vector<string> generatePalindromes(string s) {
vector<string> res;
unordered_map<char, int> m;
string t = "", mid = "";
for (auto a : s) ++m[a];
for (auto &it : m) {
if (it.second % 2 == 1) mid += it.first;
it.second /= 2;
t += string(it.second, it.first);
if (mid.size() > 1) return {};
}
permute(t, m, mid, "", res);
return res;
}
void permute(string &t, unordered_map<char, int> &m, string mid, string out, vector<string> &res) {
if (out.size() >= t.size()) {
res.push_back(out + mid + string(out.rbegin(), out.rend()));
return;
}
for (auto &it : m) {
if (it.second > 0) {
--it.second;
permute(t, m, mid, out + it.first, res);
++it.second;
}
}
}
};

C++:

class Solution {
public:
vector<string> generatePalindromes(string s) {
vector<string> res;
unordered_map<char, int> m;
string t = "", mid = "";
for (auto a : s) ++m[a];
for (auto it : m) {
if (it.second % 2 == 1) mid += it.first;
t += string(it.second / 2, it.first);
if (mid.size() > 1) return {};
}
sort(t.begin(), t.end());
do {
res.push_back(t + mid + string(t.rbegin(), t.rend()));
} while (next_permutation(t.begin(), t.end()));
return res;
}
};

  

类似题目:

[LeetCode] 266. Palindrome Permutation 回文全排列  

[LeetCode] 46. Permutations 全排列

[LeetCode] 47. Permutations II 全排列 II

[LeetCode] 31. Next Permutation 下一个排列

  

All LeetCode Questions List 题目汇总

[LeetCode] 267. Palindrome Permutation II 回文全排列 II的更多相关文章

  1. LeetCode 266. Palindrome Permutation (回文排列)$

    Given a string, determine if a permutation of the string could form a palindrome. For example," ...

  2. [LeetCode] Palindrome Permutation II 回文全排列之二

    Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...

  3. [LeetCode#267] Palindrome Permutation II

    Problem: Given a string s, return all the palindromic permutations (without duplicates) of it. Retur ...

  4. [LeetCode] Longest Palindrome 最长回文串

    Given a string which consists of lowercase or uppercase letters, find the length of the longest pali ...

  5. [LeetCode] 234. Palindrome Linked List 回文链表

    Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ...

  6. [LeetCode] Largest Palindrome Product 最大回文串乘积

    Find the largest palindrome made from the product of two n-digit numbers. Since the result could be ...

  7. LeetCode 9. Palindrome Number (回文数字)

    Determine whether an integer is a palindrome. Do this without extra space. 题目标签:Math 题目给了我们一个int x, ...

  8. [LeetCode] 9. Palindrome Number 验证回文数字

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same back ...

  9. Leetcode 9. Palindrome Number(判断回文数字)

    Determine whether an integer is a palindrome. Do this without extra space.(不要使用额外的空间) Some hints: Co ...

随机推荐

  1. css实现硬件加速

    原文请点击一下链接: http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-c ...

  2. MSDS596 Homework 9

    MSDS596 Homework 9 (Due in class on Nov 14) Fall 2017Notes. The lowest grade among all twelve homewo ...

  3. djiango-异步发送邮件--celery

    安装 pip install celery==4.2.0 # celery4.x支持django1.11以上版本 试了好几个版本 就4.2.0能发送成功 1.项目目录里新建一个celery的包cele ...

  4. getProperty获取属性值

  5. 使用GCOV进行代码覆盖率统计

    GCOV是随GCC一起发布的用于代码覆盖率统计的工具,一般配合其图形化工具LCOV一起使用. 一.安装 GCOV不需要单独安装,LCOV下载后执行sudo make install即可完成安装. 二. ...

  6. 公告 & 备注

    公告 这个\(blog\)从\(2019.12.21\)正式开始使用. 之前的博客请出门右转链接: \[\Large\texttt{my blog}\] \(:)\) 备注 近期要学的算法qwq \( ...

  7. LeetCode 1043. Partition Array for Maximum Sum

    原题链接在这里:https://leetcode.com/problems/partition-array-for-maximum-sum/ 题目: Given an integer array A, ...

  8. CDN工作机制

    CDN(content delivery network),即内容分布网络,是一种构建在现有Internet上的一种先进的流量分配网络.CDN以缓存网站中的静态数据为主,当用户请求动态内容时,先从CD ...

  9. 浅谈前端H5自定义分享实现方法

     引入jweinxin相关js文件,然后才可以做H5的分享 <script src="js/jweixin-1.2.0.js"></script> let ...

  10. 【批处理】if命令,注释方式

    If 命令 if 表示将判断是否符合规定的条件,从而决定执行不同的命令. 有三种格式:1.if "参数" == "字符串" 待执行的命令参数如果等于指定的字符串 ...