java版数据结构与算法—递归(变位字)

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("");
        }
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38799368/article/details/84350259
今日推荐