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代码质量吧:让我们疑惑的字符串拼接方式的选择
一.分析 对于一个字符串进行拼接有三种方法:加号.concat方法.及StringBuiler或StringBuffer. 1."+"方法拼接字符串 str += " ...
- UML解惑:图说UML中的六大关系--转
UML定义的关系主要有六种:依赖.类属.关联.实现.聚合和组合.这些类间关系的理解和使用是掌握和应用UML的关键,而也就是这几种关系,往往会让初学者迷惑.这里给出这六种主要UML关系的说明和类图描述, ...
- Java基础知识强化之IO流笔记02:try...catch的方式处理异常
1. 案例示例: package com.himi.trycatch; public class ExceptionDemo { public static void main(String[] ar ...
- ·数据库基本内容回顾-day16.06.30
一. 模式的定义和删除 ---创建了一个模式,就创建了一个数据库命名空间,一个框架.cascade.restrict create schema<模式名> authorization & ...
- 人工智能2:智能Agent
一.Agent基本定义 基于理性行为的Agent是本书人工智能方法的核心.Agent由传感器.执行器两个重要元件组成,具有与环境交互的能力,其能力是通过分析感知序列,经过Agent函数映射到相应的行动 ...
- 图片样式 scaleType 属性
ImageView的属性android:scaleType,即ImageView.setScaleType(ImageView.ScaleType),不同值的意义区别:
- javascript小数四舍五入
javascript小数四舍五入 1. function get(){ var s = 22.127456 + ""; var str = s.substring(0, ...
- sql数据库之间数据的转录
private void Form1_Load(object sender, EventArgs e) { BindDataBase(combDataBaseNew, , ""); ...
- codesmith的使用
新建一个C#模版. model类的模版代码如下: <%-- Name: 模型层代码生成模版 Author: XX Description: 根据数据库的内容生成模型层代码 Version: V1 ...
- HTML5触摸屏touch事件使用介绍1
市面上手机种类繁多,在触屏手机上运行的网页跟传统PC网页相比还是有很大差别的.由于设备的不同浏览器的事件的设计也不同.传统PC站的 click 和 onmouseover 等事件在一般触屏的手机上也可 ...