Palindrome Permutation II 解答
Question
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.
Answer
这道题思考起来其实不难,就是步骤比较多,要小心。
1. 判断输入是否能有permutation构成palindrome => HashMap或HashSet,这里因为判断完后还有下一步,所以采用Map
2. 根据Map获得first half of the string
3. Backtracking生成first half的permutation
4. 根据生成的permutation,补齐last half
另外解答中处理反转String的方法也值得学习:先利用原String构造一个StringBuffer,然后从后往前遍历原String,将char一一加到StringBuffer中。
public class Solution {
public List<String> generatePalindromes(String s) {
List<String> result = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
int len = s.length();
Map<Character, Integer> map = new HashMap<>();
if (!isPalindromePermutation(map, s)) {
return result;
}
char mid = '\0';
StringBuilder sb = new StringBuilder();
for (char cur : map.keySet()) {
int num = map.get(cur);
while (num > 1) {
sb.append(cur);
num -= 2;
}
if (num == 1) {
mid = cur;
}
}
Set<String> prefix = new HashSet<String>();
boolean[] visited = new boolean[sb.length()];
dfs(sb, visited, prefix, "");
for (String left : prefix) {
StringBuffer tmp = new StringBuffer(left);
if (mid != '\0') {
tmp.append(mid);
}
for (int i = left.length() - 1; i >= 0; i--) {
tmp.append(left.charAt(i));
}
result.add(tmp.toString());
}
return result;
}
private void dfs(StringBuilder sb, boolean[] visited, Set<String> result, String prev) {
if (prev.length() == sb.length()) {
result.add(prev);
return;
}
int len = sb.length();
int prevIndex = -1;
for (int i = 0; i < len; i++) {
if (visited[i]) {
continue;
}
if (prevIndex != -1 && sb.charAt(i) == sb.charAt(prevIndex)) {
continue;
}
visited[i] = true;
dfs(sb, visited, result, prev + sb.charAt(i));
visited[i] = false;
prevIndex = i;
}
}
private boolean isPalindromePermutation(Map<Character, Integer> map, String s) {
int tolerance = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
char cur = s.charAt(i);
if (!map.containsKey(cur)) {
map.put(cur, 1);
} else {
map.put(cur, map.get(cur) + 1);
}
}
for (char cur : map.keySet()) {
int num = map.get(cur);
if (num % 2 == 1) {
tolerance++;
}
}
return tolerance < 2;
}
}
Palindrome Permutation II 解答的更多相关文章
- leetcode 266.Palindrome Permutation 、267.Palindrome Permutation II
266.Palindrome Permutation https://www.cnblogs.com/grandyang/p/5223238.html 判断一个字符串的全排列能否形成一个回文串. 能组 ...
- [LeetCode] Palindrome Permutation II 回文全排列之二
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...
- 267. Palindrome Permutation II
题目: Given a string s, return all the palindromic permutations (without duplicates) of it. Return an ...
- [LeetCode] 267. Palindrome Permutation II 回文全排列 II
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...
- LeetCode Palindrome Permutation II
原题链接在这里:https://leetcode.com/problems/palindrome-permutation-ii/ 题目: Given a string s, return all th ...
- [LeetCode#267] Palindrome Permutation II
Problem: Given a string s, return all the palindromic permutations (without duplicates) of it. Retur ...
- [Swift]LeetCode267.回文全排列 II $ Palindrome Permutation II
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...
- [Locked] Palindrome Permutation I & II
Palindrome Permutation I Given a string, determine if a permutation of the string could form a palin ...
- [LeetCode] Palindrome Permutation I & II
Palindrome Permutation Given a string, determine if a permutation of the string could form a palindr ...
随机推荐
- 用java具体代码实现分数(即有理数)四则运算
用java具体代码实现分数(即有理数)四则运算 1,背景 Java老师布置了一个关于有理数运算的题目,因为参考书上有基本代码,所以自己主要是对书上代码做了一点优化,使其用户交互性更加友好以及代码封装性 ...
- Android常用ProgressDialog设置
public static ProgressDialog initDialog(Context context) { ProgressDialog progressDialog = new Progr ...
- Java 编程的动态性,第 6 部分: 利用 Javassist 进行面向方面的更改--转载
本系列的 第 4 部分和 第 5 部分讨论了如何用 Javassist 对二进制类进行局部更改.这次您将学习以一种更强大的方式使用该框架,从而充分利用 Javassist 对在字节码中查找所有特定方法 ...
- Java基础知识强化88:BigDecimal类之BigDecimal类引入和概述 以及 BigDecimal的使用(加减乘除)
1. BigDecimal类概述: 由于在运算的时候,float类型和double很容易丢失精度.所以为了能够精确的表达.计算浮点数,Java提供了BigDecimal. BigDecimal:不可变 ...
- NYOJ-569最大公约数之和
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=569 此题目可以用筛选法的思想来做,但是用到一个欧拉函数 gcd(1,12)=1,gcd( ...
- Centos6 安装vnc
Centos6 安装vnc 1. 安装 使用yum方式安装 yum install tigervnc-server tigervnc #启动 vncserver #重启动 /etc/init.d/vn ...
- Java数据库连接之配置ODBC数据源
java使用JDBC-ODBC桥接连接SQLServer数据库需要配置ODBC数据源,配置步骤如下: 1.进入控制面板,找到管理工具 2.看到ODBC数据源,有64位和32位的,如果你的数据库是64位 ...
- 7、第七节课,js逻辑运算
1.条件语句 function MyClick() { ; ; ; if (iNum1==iNum2) { iNum2=iNum3; } alert(iNum2); } 2. iNum3=iNum1& ...
- 使用HighCharts实现实时数据展示
在众多的工业控制系统领域常常会实时采集现场的温度.压力.扭矩等数据,这些数据对于监控人员进行现场态势感知.进行未来趋势预测具有重大指导价值.工程控制人员如果只是阅读海量的数据报表,对于现场整个态势的掌 ...
- sql sever 随机查询
Select * From TableName Order By NewID() NewID()函数将创建一个 uniqueidentifier 类型的唯一值.上面的语句实现效果是从Table中随 ...