[LeetCode 267] Palindrome Permutation II
来源:互联网 发布:中国有多安全美国知乎 编辑:程序博客网 时间:2024/05/09 09:17
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
Solution:
odd time char must be in the middle position, similar with Palindrome Permutation Question, can use int array to store number of char appear time.
public List<String> generatePalindromes(String s) { int[] map = new int[256]; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for(char c: s.toCharArray()) { map[c]++; min = Math.min(min, c); max = Math.max(max, c); } int count = 0; List<String> res = new ArrayList<>(); int oddIndex = 0; for(int i=min;i<=max;i++) { if(count ==0 && map[i]%2==1) { oddIndex = i; count++; }else if(map[i]%2 == 1){ return res; } } String cur = ""; if(count==1) { cur += (char)oddIndex; map[oddIndex]--; } dfs(map, cur, s, res); return res; } private void dfs(int[] map, String cur, String s, List<String> res) { if(cur.length()==s.length()) { res.add(cur); return; } for(int i=0;i<map.length;i++) { if(map[i]>0) { map[i]-=2; cur = (char)i + cur + (char)i; dfs(map, cur, s, res); cur = cur.substring(1, cur.length()-1); map[i]+=2; } } }
0 0
- [LeetCode 267] Palindrome Permutation II
- LeetCode 267. Palindrome Permutation II
- LeetCode 267. Palindrome Permutation II
- Leetcode Palindrome Permutation I & II
- LeetCode 题解(242) : Palindrome Permutation II
- [leetcode] 267. Palindrome Permutation II 解题报告
- [Leetcode] 267. Palindrome Permutation II 解题报告
- [LeetCode267]Palindrome Permutation II
- Palindrome Permutation II
- Palindrome Permutation II
- Palindrome Permutation II
- 267. Palindrome Permutation II
- 267. Palindrome Permutation II
- LeetCode 267. Palindrome Permutation II(对称排列)
- Leetcode: Palindrome Permutation
- *LeetCode-Palindrome Permutation
- [LeetCode 266]Palindrome Permutation
- Leetcode - 266. Palindrome Permutation
- 笔记:在C#中进行事务处理
- 关于DBA_TABLES中SECONDARY列的含义
- layoutSubViews
- iOS Orientation 屏幕旋转
- QQ粘性效果计算原理
- [LeetCode 267] Palindrome Permutation II
- 初始化方法awakeFromNib,initWithFrame
- 不能直接给self.center.x赋值
- storyboard的根控制器在这个时候才会添加到窗口
- 前端神技能
- 按钮的监听和touch方法
- 开根号
- 设置按钮居中
- Java对象的引用与垃圾回收