java 写一个字符串的全排序 用for循环
时间: 2023-12-08 20:06:16 浏览: 34
以下是使用for循环实现字符串的全排列的Java代码:
```java
import java.util.Scanner;
public class StringPermutation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个字符串:");
String s = input.nextLine();
System.out.println("字符串的全排列为:");
permutation(s);
}
public static void permutation(String s) {
int len = s.length(); // 字符串长度
int[] p = new int[len]; // 存放每个字符的下标
for (int i = 0; i < len; i++) {
p[i] = i; // 初始化下标数组
}
while (true) {
// 输出当前排列
for (int i = 0; i < len; i++) {
System.out.print(s.charAt(p[i]));
}
System.out.println();
// 查找下一个排列
int i = len - 2;
while (i >= 0 && p[i] >= p[i + 1]) {
i--;
}
if (i < 0) {
break; // 已经是最后一个排列了
}
int j = len - 1;
while (p[j] <= p[i]) {
j--;
}
// 交换 p[i] 和 p[j]
int temp = p[i];
p[i] = p[j];
p[j] = temp;
// 反转 p[i+1] 到 p[len-1]
for (int x = i + 1, y = len - 1; x < y; x++, y--) {
temp = p[x];
p[x] = p[y];
p[y] = temp;
}
}
}
}
```
这个程序中,使用了一个整型数组p来存放每个字符的下标,通过不断交换和反转p数组中的元素来实现字符串的全排列。