267. Palindrome Permutation II

本文介绍了一种生成字符串所有可能的回文排列的方法,并提供了一个详细的Java实现案例。通过计算字符出现次数来确定中间字符及半回文串,利用递归深度优先搜索(DFS)生成半回文串的所有唯一排列。

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

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:

  1. If a palindromic permutation exists, we just need to generate the first half of the string.
  2. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.

Solution:
First Compute the occurence and the middle of the palindrome.
Then get the first half of the  palindrome by dfs.
Use the first half to generate the full palindrome.

public class Solution {
    public List<String> generatePalindromes(String s) {
        int[] count = new int[128];
        for(char c : s.toCharArray()){
            count[c] += 1;
        }
        String middle = "";
        for(int i = 0 ; i < 128; i++){
            if((count[i] & 1) != 0){
                if(middle.length() > 0) return new ArrayList<String>();
                else middle = "" + (char) i;
            } 
            count[i] >>= 1;
        }
        List<String> ret = new ArrayList<String>();
        helper(ret,new StringBuilder(),count,s.length() / 2);
        for(int i = 0; i < ret.size(); i++){
            ret.set(i ,ret.get(i) + middle + new StringBuilder(ret.get(i)).reverse().toString());
        }
        return ret;
    }
    
    public void helper(List<String> ret, StringBuilder path, int[] count, int len){
        if(len == 0){
            ret.add(path.toString());
            return ;
        }
        for(int i = 0 ; i < count.length; i++){
            if(count[i] > 0){
                path.append((char) i);
                count[i] -= 1;
                helper(ret,path,count,len - 1);
                count[i] += 1;
                path.deleteCharAt(path.length() - 1);
            }
        }
        
    }
}


 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值