java三层怎么串_Java求一个字符串的所有排列,独创思路(不用递归,不用三层循环)...

求一个字符串的所有排列,网上找到的所有方法要么是递归,要么是三层for循环。

我这个方法不需要递归,只要两层for循环,思路非常独特。缺点是字符串长度较长时执行时间可能要几万年。但毕竟是自己的原创思路,且网上没有这个算法,姑且记录下来。

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

public class Main {

private List elements = new ArrayList<>();

private int length;

public Main(String input) {

length = input.length();

for (int i = 0; i < length; i++) {

elements.add("");

}

for (int i = 0; i < length; i++) {

String element = input.substring(i, i + 1);

elements.set(i, element);

}

}

private List permutate() {

List permutations = new ArrayList<>();

for (int p = 0; p < Short.MAX_VALUE; p++) { // 字符串较长时需要改成一个很大的数

StringBuilder randomSb = new StringBuilder();

for (int i = 0; i < length; i++) {

int r = new Random().nextInt(length);

if (!randomSb.toString().contains(elements.get(r))) {

randomSb.append(elements.get(r));

}

}

if (!permutations.contains(randomSb.toString()) && randomSb.toString().length() == length) {

permutations.add(randomSb.toString());

}

}

return permutations;

}

public static void main(String[] args) {

Main main = new Main("ABCDE");

List result = main.permutate();

for (String s : result) {

System.out.println(s);

}

System.out.println("Number of permutations is " + result.size());

}

}

执行结果:

BEDCA

EBADC

ADBCE

DCEBA

ECDAB

DEACB

DACEB

CBDAE

EDACB

DEBCA

ACBDE

ABCDE

EABDC

CDAEB

DCBAE

ACDEB

BACED

DECBA

DECAB

CEDAB

DBECA

CEDBA

DAEBC

DCAEB

AEBDC

ADCBE

CDEAB

EDBCA

AEBCD

BECDA

CBEDA

BACDE

CEBDA

BADCE

BDCEA

DCABE

BDAEC

BEACD

BCEDA

DBCAE

DABEC

BCDAE

BCEAD

CEABD

BADEC

EBACD

CEADB

ACEBD

CADBE

BECAD

EADBC

ADBEC

ACBED

EBCAD

DABCE

EACDB

EABCD

ABECD

AECBD

ECDBA

BDEAC

DAECB

DBAEC

DBCEA

ABDEC

AECDB

CAEDB

DACBE

EADCB

BDECA

CABDE

CBADE

EDCBA

BEDAC

EDBAC

EBCDA

ADCEB

ECABD

ACDBE

ABEDC

BDACE

BDCAE

ECBDA

BCDEA

EBDAC

CBDEA

ECADB

ECBAD

CADEB

DEABC

BAEDC

CEBAD

BEADC

EDABC

CDBAE

BCAED

AEDBC

DCEAB

CDEBA

ADECB

DEBAC

DCBEA

AEDCB

DBEAC

CDABE

BCADE

CAEBD

ACEDB

CBAED

EACBD

ADEBC

EBDCA

CBEAD

CABED

ABDCE

BAECD

DBACE

ABCED

EDCAB

CDBEA

Number of permutations is 120

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值