六月的第一篇博客
昨天笔试的时候遇到一个题目,题目的大致意思如下
给一个字符串,其中字符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