[LeetCode] 267. Palindrome Permutation II 回文全排列 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 [].
Hint:
- If a palindromic permutation exists, we just need to generate the first half of the string.
- 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的更多相关文章
- LeetCode 266. Palindrome Permutation (回文排列)$
Given a string, determine if a permutation of the string could form a palindrome. For example," ...
- [LeetCode] Palindrome Permutation II 回文全排列之二
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...
- [LeetCode#267] Palindrome Permutation II
Problem: Given a string s, return all the palindromic permutations (without duplicates) of it. Retur ...
- [LeetCode] Longest Palindrome 最长回文串
Given a string which consists of lowercase or uppercase letters, find the length of the longest pali ...
- [LeetCode] 234. Palindrome Linked List 回文链表
Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ...
- [LeetCode] Largest Palindrome Product 最大回文串乘积
Find the largest palindrome made from the product of two n-digit numbers. Since the result could be ...
- LeetCode 9. Palindrome Number (回文数字)
Determine whether an integer is a palindrome. Do this without extra space. 题目标签:Math 题目给了我们一个int x, ...
- [LeetCode] 9. Palindrome Number 验证回文数字
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same back ...
- Leetcode 9. Palindrome Number(判断回文数字)
Determine whether an integer is a palindrome. Do this without extra space.(不要使用额外的空间) Some hints: Co ...
随机推荐
- 关于立即调用的函数表达式(IIFE)
在 JavaScript 中,圆括号 () 是一种运算符,跟在函数名之后,表示调用该函数.比如,print() 就表示调用 print 函数 有时,我们需要在定义函数之后,立即调用该函数,例如: fu ...
- django项目简单调取百度翻译接口
1,建路由: 2,写方法: def fanyi(request): import requests import json content = request.POST.get('content') ...
- The Sum of the k-th Powers(Educational Codeforces Round 7F+拉格朗日插值法)
题目链接 传送门 题面 题意 给你\(n,k\),要你求\(\sum\limits_{i=1}^{n}i^k\)的值. 思路 根据数学知识或者说题目提示可知\(\sum\limits_{i=1}^{n ...
- docker学习2-快速搭建centos7-python3.6环境
前言 当我们在一台电脑上搭建了python3.6的环境,下次换了个电脑,或者换成linux的系统了,又得重新搭建一次,设置环境变量.下载pip等操作. 好不容易安装好,一会Scrips目录找不到pip ...
- Vue的参数请求与传递
Vue不同模板之间的参数传递 页面路由带参数的跳转: 参数接收: Vue向服务器请求资源的两种方式 VUE-RESOURCE 1.Vue.js是数据驱动的,这使得我们并不需要直接操作DOM,如果我们不 ...
- 关于Java的i++和++i的区别
之前对于 i++ 和 ++i 的理解就是: int i=1,a=0; 1.i++ 先运算在赋值,例如 a=i++,先运算a=i,后运算i=i+1,所以结果是a==1 2.++i 先赋值在运算,例如 a ...
- web自动化测试-自动化测试模型介绍
一.线性测试 什么是线性测试? 通过录制或编写对应用程序的操作步骤产生相应的线性脚本,每个测试脚本相对独立,不产生依赖和调用,单纯的来模拟用户完整的操作场景 缺点 1.开发成本高,测试用例之间存在重复 ...
- janusgraph-创建索引出现GraphIndexStatusReport[success=false, indexName='mixedvlabel', targetStatus=[REGISTERED], notConverged={vlabel=INSTALLED}, converged={}, elapsed=PT1M0.07S]
参考网址: https://www.cnblogs.com/Uglthinx/p/9630779.html 原因:我的是事务没有完全关闭 解决办法: 创建一个混合索引: // 在graph中有事务执行 ...
- Net-NTLMv1的利用思路
Net-NTLMv1的加密方法: 客户端向服务器发送一个请求 服务器接收到请求后,生成一个16位的Challenge,发送回客户端 客户端接收到Challenge后,使用登录用户的密码hash对Cha ...
- 分析第一个Android程序
项目结构切换Project, 项目真实目录结构 { 1. .gradle和idea 两个目录放置的都是Android Studio 自动生成的一些文件,我们无需关心,也不要去手动编辑. 2.AP ...