例如 輸入“abc”,打印所有可能出現的組合情況,并且消除重復值。
所謂排列組合如下:
排列組合,字符串:abc
bca
acb
abc
cba
bac
cab
排列組合個數:6
實現代碼(結合Java8 lambda表達式實現)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
import org.junit.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class test2 { @Test public void test3() { String input= "abc" ; //1.開始排列 List<String> sortResult = sort(input); System.out.println( "排列組合,字符串:" +input); //2.消除重復列 HashSet h = new HashSet(sortResult); sortResult.clear(); sortResult.addAll(h); //3.打印輸出 sortResult.forEach(e -> System.out.println(e)); //4.打印個數 System.out.println( "排列組合個數:" + sortResult.size()); } private List<String> sort(String input) { List<String> sortList = new ArrayList(); if (input == null || "" .equals(input)) { System.out.println( "提示:您輸入了空字符,請輸入有效值!" ); return new ArrayList(); } char leftChar = input.charAt( 0 ); if (input.length() > 1 ) { String rightString = input.substring( 1 , input.length()); List<String> rightStringSortedList = sort(rightString); rightStringSortedList.forEach((e) -> { for ( int i = 0 ; i < e.length() + 1 ; i++) { sortList.add( new StringBuffer(e).insert(i, leftChar).toString()); } }); } else { sortList.add(String.valueOf(leftChar)); } return sortList; } } |
如有更簡潔的代碼實現,請不要吝嗇,貼出來分享下。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/u013410747/article/details/51579601