Java: A way to arrange and combine strings
- 2021-01-19 22:17:13
- OfStack
For example, enter "abc" to print out all possible combinations and eliminate duplicate values.
The so-called permutations and combinations are as follows:
Permutation and combination, string :abc
bca
acb
abc
cba
bac
cab
Number of permutations and combinations: 6
Implementation code (combined with Java8 lambda expression implementation)
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. Start to arrange
List<String> sortResult = sort(input);
System.out.println(" Permutation and combination , string :"+input);
//2. Eliminate duplicate columns
HashSet h = new HashSet(sortResult);
sortResult.clear();
sortResult.addAll(h);
//3. A printout
sortResult.forEach(e -> System.out.println(e));
//4. Print the number of
System.out.println(" Number of permutations and combinations: " + sortResult.size());
}
private List<String> sort(String input) {
List<String> sortList = new ArrayList();
if (input == null || "".equals(input)) {
System.out.println(" Tip: You entered a null character , Please enter valid values! ");
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;
}
}
If there is a more concise code implementation, please do not be stingy, post and share.