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. Kotlin函数与Lambda表达式深入

    Kotlin函数: 关于Kotlin函数在之前也一直在用,用fun来声明,回忆下: 下面再来整体对Kotlin的函数进行一个学习. 默认参数(default arguments): 先来定义一个函数: ...

  2. ASP.NET Core 类库中取读配置文件 appsettings.json

    首先引用NuGet包 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json Microsoft.Exte ...

  3. Python应用-完成简单邮件发送功能

    项目中有时候需要用脚本来自动发送邮件,而用Python来发送邮件十分的方便,代码如下: #!/usr/bin/python #coding:utf-8 import smtplib from emai ...

  4. Python开发笔记之-浮点数传输

    操作系统 : CentOS7.3.1611_x64 gcc版本 :4.8.5 Python 版本 : 2.7.5 思路如下 : 1.将浮点数a通过内存拷贝,赋值给相同字节的整型数据b: 2.将b转换为 ...

  5. Python库资源大全【收藏】

    本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQuant整理加工而成,欢迎扩散.欢迎补充! 对机器学习.深度学习在量化投资中应用感兴趣的 ...

  6. oracle plsql 实现apriori算法

    对apriori关联关系算法研究了一段时间,网上能搜到的例子,大部分是python写的,数据集长得像下面这样: [[I1,I2,I5],[I2,I4],[I2,I3],[I1,I2,I4],[I1,I ...

  7. [Codeforces 1242C]Sum Balance

    Description 题库链接 给你 \(k\) 个盒子,第 \(i\) 个盒子中有 \(n_i\) 个数,第 \(j\) 个数为 \(x_{i,j}\).现在让你进行 \(k\) 次操作,第 \( ...

  8. AtCoder Beginner Contest 132 解题报告

    前四题都好水.后面两道题好难. C Divide the Problems #include <cstdio> #include <algorithm> using names ...

  9. 通过HttpServletRequest重写+filter 添加header

    问题说明 需要做的事情比较简单,就是通过filter 重写httpservletrequest ,同时给予request 添加header 主要是通过HttpServletRequestWrapper ...

  10. CSS3背景图片(多重背景、起始位置、裁剪、尺寸)

    一.多重背景图片 ①CSS3允许我们在一个元素上添加多个图片 ②多重背景可以把多个图片资源添加到background属性上,用逗号隔开,然后用background-position把他们定位到你想要的 ...