重复单词的变化

时间:2014-03-09 06:57:35

标签: java

如何使用重复值对变量进行编码,其中值为String,而不是char? 使用此代码:

import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        LinkedList<char[]> items = new LinkedList<char[]>();
        char[] item = new char[3];
        char[] input = {'A', 'B'};



        for (char[] rep : items) {
            System.out.println(rep);
        }
         rep(items, input, item, 0);
    }

    private static void rep(LinkedList<char[]> reps, char[] input, char[] item, int count){
        if (count < item.length){
            for (int i = 0; i < input.length; i++) {
                item[count] = input[i];
                rep(reps, input, item, count+1);
            }
        }else{
            reps.add(item.clone());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定你想要什么,所以我只是把你的代码,转换器char改为String并调整了打印循环:

import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        LinkedList<String[]> items = new LinkedList<String[]>();
        String[] item = new String[3];
        String[] input = {"john", "paul"};

        rep(items, input, item, 0);

        for (String[] rep : items) {
            for (String str : rep)
                System.out.print(str+" ");
            System.out.println();
        }
         rep(items, input, item, 0);
    }

    private static void rep(LinkedList<String[]> reps, String[] input, String[] item, int count){
        if (count < item.length){
            for (int i = 0; i < input.length; i++) {
                item[count] = input[i];
                rep(reps, input, item, count+1);
            }
        }else{
            reps.add(item.clone());
        }
    }
}

这是输出:

john john john 
john john paul 
john paul john 
john paul paul 
paul john john 
paul john paul 
paul paul john 
paul paul paul 

这就是你想要的吗?