用户输入字符串,输出所有排列。这里将字符串转换为数组:
使用递归的方法实现:
希望输入的字符少一点,比如代码中注释的"abc"
import java.util.Scanner;
public class Test2RecursionStringSort
{
private static int count = 0;
public static void main(String[] args)
{
System.out.println("系统等待用户输入一行字符串: ");
Scanner scanner = new Scanner(System.in);
String in = scanner.nextLine();
// String in = "abc";
allStringSorts(in.toCharArray(), 0, in.length() - 1);
System.out.println("排列的总个数: " + count);
}
private static void allStringSorts(char[] array, int low, int high)
{
if(low == high)
{
count ++;
System.out.print("第" + count + "次序列: " );
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
System.out.println();
}
else
{
for(int i = 0; i <= high; i++)
{
for(int j = 0; j < high; j++)
{
char temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
allStringSorts(array, 0, high -1);
}
}
}
}