java字符串排列组合
时间: 2023-09-01 14:08:50 浏览: 46
你可以使用递归的方法来实现字符串的排列组合。以下是一个示例代码:
```java
public class StringPermutation {
public static void main(String[] args) {
String str = "abc";
permutation(str.toCharArray(), 0);
}
public static void permutation(char[] str, int index) {
if (index == str.length - 1) {
System.out.println(String.valueOf(str));
} else {
for (int i = index; i < str.length; i++) {
swap(str, index, i);
permutation(str, index + 1);
swap(str, index, i);
}
}
}
public static void swap(char[] str, int i, int j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
```
这段代码会输出字符串 "abc" 的所有排列组合:abc、acb、bac、bca、cab 和 cba。
需要注意的是,这段代码只适用于输入字符串中没有重复字符的情况。如果输入字符串中有重复字符,需要对代码进行修改。