全排列-给一个字符串,其中字符aeio不能排在一起。然后输出这个字符串的所有排列的总数

本文介绍了一种解决特定字符串排列问题的算法,该问题要求在排列过程中避免特定字符(aeio)相邻。通过使用全排列方法结合HashSet去重,确保了最终结果的正确性和独特性。代码示例展示了如何在Java中实现这一算法。

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

六月的第一篇博客
昨天笔试的时候遇到一个题目,题目的大致意思如下
给一个字符串,其中字符aeio不能排在一起。然后输出这个字符串的所有排列的总数
输入n,接下来输入n行字符串
输出每行的排列可能。

笔者这里采用的全排列来做的。
在排列的过程中做两件事情:

  • 去重,采用HashSet
  • aeio不能排在一起

代码如下

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

/**
 * @author XiangYida
 * @ve你rsion 2019/5/31 20:52
 */
public class T2 {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int i = Integer.parseInt(reader.readLine());
        String[] strings = new String[i];
        for (int j = 0; j < i; j++)strings[j] = reader.readLine();
        for (int j = 0; j < i; j++) {
            String s=strings[j];
            int[]n=new int[]{0};
            test(s.toCharArray(),0,new HashSet<String>(),n);
            System.out.println(n[0]);
        }
    }
    //全排列,这里的n就是排列的总数
    public static void test(char[]nums, int k, HashSet<String>set,int[]n){
        if(k==nums.length-1){
            String string=new String(nums);
            char[]chars=string.toCharArray();
            boolean judge=true;
            //判断字符aeio是否在一起
            for (int i = 0; i < chars.length; i++) {
                char c=chars[i];
                if(c=='a'||c=='e'||c=='i'||c=='o'){
                    if(i+1<chars.length){
                        char b=chars[i+1];
                        if(c!=b&&(b=='a'||b=='e'||b=='i'||b=='o')){
                            judge=false;
                            break;
                        }
                    }
                }
            }
            //同时去重
            if(judge&&!set.contains(string)){
                set.add(string);
                n[0]++;
            }
        }
        else {
            for (int i = k; i < nums.length ;i++) {
                swap(nums,k,i);
                test(nums,k+1,set,n);
                swap(nums,i,k);
            }
        }
    }
    public static void swap(char[]c,int i,int j){
        char temp=c[i];
        c[i]=c[j];
        c[j]=temp;
    }
}

这里打印一下排列的结果测试一下

输入:1
输入:aeecc
输出:
aceec
acece
accee
eecac
eecca
ececa
ecace
ceeca
cacee
9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值