LeetCode Palindrome Permutation II

本文提供了一种解决LeetCode上“回文排列II”问题的方法,通过判断字符串能否形成回文串并利用递归进行全排列,最终得到所有不重复的回文排列组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里: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.

For example:

Given s = "aabb", return ["abba", "baab"].

Given s = "abc", return [].

题解:

Palindrome Permutation相似.

先判断是否palindrome, 若不是返回空的res. 若是,先判断是否有一个奇数位,若有,改char放中间. 然后两边分别加.

Time Complexity: O(2^n). Space: O(n)层stack.

AC Java:

 1 public class Solution {
 2     public List<String> generatePalindromes(String s) {
 3         List<String> res = new ArrayList<String>();
 4         int [] map = new int[256];
 5         for(int i = 0; i<s.length(); i++){
 6             map[s.charAt(i)]++;
 7         }
 8         int count = 0;
 9         int po = 0;
10         for(int i = 0; i<256; i++){
11             if(count == 0 && map[i]%2 == 1){
12                 count++;
13                 po = i;
14             }else if(map[i]%2 == 1){
15                 return res;
16             }
17         }
18         
19         String cur = "";
20         if(po != 0){
21             map[po]--;
22             cur = "" + (char)po;
23         }
24         DFS(map, s.length(), cur, res);
25         return res;
26     }
27     
28     private void DFS(int [] map, int len, String cur, List<String> res){
29         if(cur.length() == len){
30             res.add(new String(cur));
31             return;
32         }
33         for(int i = 0; i<map.length; i++){
34             if(map[i] <= 0){
35                 continue;
36             }
37             map[i] -= 2;
38             cur = (char)i + cur + (char)i;
39             DFS(map, len, cur, res);
40             cur = cur.substring(1, cur.length()-1);
41             map[i] += 2;
42         }
43     }
44 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5265380.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值