java字符串排列组合
时间: 2023-09-01 14:08:40 浏览: 199
要生成Java字符串的排列组合,可以使用递归的方法。
以下是一个示例代码,可以输出字符串的所有排列组合:
```java
import java.util.HashSet;
import java.util.Set;
public class Permutations {
public static Set<String> generatePermutations(String str) {
Set<String> set = new HashSet<>();
if (str == null) {
return set;
} else if (str.length() == 0) {
set.add("");
return set;
}
char firstChar = str.charAt(0);
String remainingStr = str.substring(1);
Set<String> permutations = generatePermutations(remainingStr);
for (String permutation : permutations) {
for (int i = 0; i <= permutation.length(); i++) {
set.add(insertCharAt(permutation, firstChar, i));
}
}
return set;
}
private static String insertCharAt(String str, char c, int index) {
String start = str.substring(0, index);
String end = str.substring(index);
return start + c + end;
}
public static void main(String[] args) {
Set<String> permutations = generatePermutations("abc");
for (String permutation : permutations) {
System.out.println(permutation);
}
}
}
```
输出结果为:
```
acb
cab
bac
cba
bca
abc
```
阅读全文