LeetCode 267. Palindrome Permutation II

原题链接在这里:https://leetcode.com/problems/palindrome-permutation-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.

Example 1:

"aabb"
["abba", "baab"]

Example 2:

"abc"
[]

题解:

先判断是否palindrome, 若不是返回空的res.

若是,先判断是否有一个奇数位,若有,改char放中间. 然后两边分别加.

Note: check to find single char after updating the map.

Don't forget to minus its count by 1 after appending it to item.

Time Complexity: O(2^n). n = s.length().

Space: O(n). stack space.

AC Java:

复制代码
 1 class Solution {
 2     public List<String> generatePalindromes(String s) {
 3         List<String> res = new ArrayList<>();
 4         if(s == null || s.length() == 0){
 5             return res;
 6         }
 7         
 8         int [] count = new int[256];
 9         int n = s.length();
10         int po = -1;
11         for(int i = 0; i<n; i++){
12             count[s.charAt(i)]++;
13         }
14         
15         int oneCount = 0;
16         for(int i = 0; i<256; i++){
17             oneCount += count[i]%2;
18             
19             if(count[i]%2 == 1){
20                 po = i;
21             }
22         }
23         
24         if(oneCount > 1){
25             return res;
26         }
27         
28         String init = "";
29         if(po != -1){
30             init += (char)po;
31             count[po]--;
32         }
33         
34         dfs(count, init, n, res);
35         return res;
36     }
37     
38     private void dfs(int [] count, String cur, int n, List<String> res){
39         if(cur.length() == n){
40             res.add(cur);
41             return;
42         }
43         
44         for(int i = 0; i<count.length; i++){
45             if(count[i] > 0){
46                 count[i] -= 2;
47                 dfs(count, (char)i+cur+(char)i, n, res);
48                 count[i] += 2;
49             }
50         }
51     }
52 }
复制代码

Palindrome Permutation相似. 

posted @   Dylan_Java_NYC  阅读(521)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
点击右上角即可分享
微信分享提示