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 ...
随机推荐
- Android(java)学习笔记251:ContentProvider使用之添加数据到联系人(掌握)
1.添加联系人逻辑思路 (1)首先在raw_contacts创建一个新的id (2)在data表里面添加这个id对应的数据 2.下面通过一个案例,说明一下如何添加一条数据到联系人: (1)首先我们关注 ...
- 织梦DEDECMS {dede:field name='position'/}标签增加其它属性的
在默认情况下,织梦(DedeCms)系统当前位置的调用标签为: {dede:field name='position'/} 在这种默认的情况下,生成后的代码大致为如下格式: 主页 > 应用软件 ...
- Examples_08_03
访问本地程序.http://192.168.1.103/preg_match/test.php,如果换成localhost或者127.0.0.1,则会导致无法访问. http://blog.csdn. ...
- PHP语言中使用JSON
原文地址:http://www.ruanyifeng.com/blog/2011/01/json_in_php.html 在PHP语言中使用JSON 目前,JSON已经成为最流行的数据交换格式之一,各 ...
- Android Studio Gradle 版本不同报错解决方法
由于GFW的原因,我们在使用as时经常出现失败,或者第一次新建工程不成功. 很多博客上已经提到了如何解决第一次新建工程Gradle构建的问题,那么在打开别的工程时依旧会报错 "Failed ...
- java rmi 小记
最近在搞Quartz任务监控管理,碰到了jmx,后来发现Quartz对jmx的支持不是很好,介绍的文档也比较少,另外Quartz可以很方便的支持rmi于是就看了一下rmi.下面把写的一些测试小例子附上 ...
- Oracle 错误码
Oracle作为一款比较优秀同时也比较难以掌握的大型数据库,在我们学习使用的过程中,不可避免的会遇到一些错误,为此 Oracle 给出了一套完备的错误消息提示机制 我们可以根据Oracle给出的消息提 ...
- 如何实现一个通用的IHttpHandler 万能的IHttpHandler HttpWebRequest文件上传
昨天遇到一个比较奇怪的需求,大致是需要在服务器上部署一个http服务,但是服务的具体功能不知道,以后在客服端实现.这里介绍一下系统背景,有一个系统运(部署在美国)行了很多年了,给系统产生了很多文件,现 ...
- geoserver + postgis+postgresql+agslib.swc
运用开源的geoserver+postgis+postgresql+arcgis for flex api 开发地图应用系统. 1.Geoserver GeoServer 是 OpenGIS Web ...
- PreparedStatement可以有效地防止sql被注入
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import jav ...