递归-全排列

        输入字符串,得到字符串的全排列。此为robert lafore著的Data Structures&Algorithms In Java中的解法,不过没有排除重复字母的情况。

/*
 * 递归程序 实现字符串的全排列
 */
public class Anagram {
	/*
	 * 输入字符串的长度 
	 */
	static int size;
	static int count;
	static char[] arrChar = new char[100];
	
	public static void main(String[] args) throws IOException 
	{
		System.out.print("Enter a word: ");
		//获取输入字符串
		String input = getString();
		size = input.length();
		count = 0;
		for(int i=0;i<size;i++)
		{
			arrChar[i] = input.charAt(i);
		}
		doAnagram(size);
	}

	private static void doAnagram(int newSize) 
	{
		if(newSize==1)
		{
			return;
		}
		for(int j=0;j<newSize;j++)
		{
			doAnagram(newSize-1);
			if(newSize==2)
				{
					display();
				}
			rotate(newSize);
		}
	}

	private static void rotate(int newSize) 
	{
		int j;
		int position = size - newSize;
		char temp = arrChar[position];
		for(j=position+1;j<size;j++)
		{	
			//将数组中的元素整体左移
			arrChar[j-1] = arrChar[j];
		}
               //首元素移到最后位置
		arrChar[j-1] = temp;
	}

	private static void display()
	{
		System.out.print(++count + " ");
		for(int j=0;j<size;j++)
		{
			System.out.print(arrChar[j]);
		}
		System.out.print(" ");
		if(count%6 == 0)System.out.println();
	}
      //获取输入字符串
	private static String getString() throws IOException {
		InputStreamReader in = new InputStreamReader(System.in);
		BufferedReader buffer = new BufferedReader(in);
		String s = buffer.readLine();
		return s;
	}
}
 

你可能感兴趣的:(J#)