java版資料結構與演算法—遞迴(變位字)
阿新 • • 發佈:2018-11-29
package com.zoujc.triangle;
import java.io.IOException;
/**
* 變位字(遞迴的效率並不如for迴圈高)
*/
class AnagramApp {
static int size;
static int count;
static char[] arrChar = new char[100];
public static void main(String[] args) throws IOException{
String str = "word";
size = str.length();
count = 0;
for(int i=0;i<size;i++){
arrChar[i] = str.charAt(i);
}
doAnagram(size);
}
//變位顛倒
public static void doAnagram(int newSize){
if(newSize == 1){
return;
}
for(int i=0;i<newSize;i++){
doAnagram (newSize - 1);
if(newSize == 2){
displayWord();
}
rotate(newSize);
}
}
//轉動
public static void rotate(int newSize){
int i;
int position = size - newSize;
char temp = arrChar[position];
for(i=position+ 1;i<size;i++){
arrChar[i-1] = arrChar[i];
}
arrChar[i-1] = temp;
}
public static void displayWord(){
if(count < 99){
System.out.print(" ");
}
if(count < 9){
System.out.print(" ");
}
System.out.print(++count + " ");
for (int i=0;i<size;i++){
System.out.print(arrChar[i]);
}
System.out.print(" ");
System.out.flush();
if(count %6 == 0){
System.out.println("");
}
}
}