输入:单词的字符串。打印给定字符串的所有重新排列而不重复。

我正在尝试用 Java 实现这个,但不知道如何实现。有什么建议么?

例子。

输入:

ABC

输出:

abc
acb
bac
bca
cab
cba

输入:

艾布

输出:

啊啊 啊啊


潇湘沐
浏览 101回答 1
1回答

明月笑刀无情

这是我能想到的最简单的方法&nbsp;String str= "abc";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ArrayList<String> letters = new ArrayList<String>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HashSet<String> combinations = new HashSet<String>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i<str.length();i++) {//Break String into letters&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; letters.add(str.substring(i,i+1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i = (str.length()*2)+1;i>0;i--) {//Will loop through maximum possible outcomes&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String result = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String bin = Integer.toBinaryString(i);//System.out.println(bin);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while(bin.length()<3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bin="0"+bin;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int b = bin.length();b>0;b--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(bin.substring(b-1,b).equals("1"))result = result.concat(letters.get(b-1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int b = bin.length();b>0;b--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(bin.substring(b-1,b).equals("0"))result = result.concat(letters.get(b-1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; combinations.add(result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(String c : combinations) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(c);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }它使用二进制循环遍历原始字符串的数组,然后将结果添加到哈希集以删除重复项
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java