2012-02-10 25 views
3

我不知道爲什麼我不能在我的腦海中工作這個。通過數組的Java增量字符串

我有一個字符數組,在我的Java代碼..

private String[] letters = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", 
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" 
}; 

我需要做的是遍歷字符串建設爲每個可能的配置。

實施例:

一個 AA AB 交流 。 。 。 aaa aab aac 。 。 。 。 aba abc

等等直到n長度。

任何人都可以指出我對這個問題的看法。

乾杯

+0

@paislee如果n給出了最大長度則有數量有限並不是無限的可能性。 – Jesper 2012-02-10 19:31:32

回答

2

另一種遞歸方法。我正在從@liwp的另一個方向工作。有一個小優點,我只分配一個輸出ArrayList。此外,爲了簡單起見,我只是把數字0 ... 9在這個例子中

static public void combos(String[] inputs, List<String> outputs, String preface, int maxDepth) { 
     if (preface.length() >= maxDepth) 
      return; 
     for (String s : inputs) { 
      // swap the order of these two lines if you want depth first 
      outputs.add(preface+s); 
      combos(inputs, outputs, preface+s, maxDepth); 
     }  
    } 


    public static void main(String[] args) { 
     String[] numbers = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; 
     ArrayList<String> outputs = new ArrayList<String>(); 
     combos(numbers, outputs, "", 3); 
     System.out.println(outputs); 

    } 

會打印出

[0, 00, 000, 001, 002, 003, 004, 005, 006, 007, 008, 009, 01, 010, 011... 
+0

哎呀,我忘了字符串'n'。也就是說,我的解決方案只產生長度爲'n'的排列。 – liwp 2012-02-10 20:32:08

+0

編輯它做n的字符串,感謝您的幫助。很棒! – jlabroy 2012-02-10 20:42:01

+0

我應該指出,我的解決方案對'permutations()'進行'n'調用,而@ user949300的解決方案對'combos()'進行'inputs.length^n'調用。 OTOH @ user949300的解決方案會生成請求的輸出順序,而我的解決方案會在較長的字符串之間插入較短的字符串。 – liwp 2012-02-10 21:53:09

0

如果你並不需要很長的序列可以使用遞歸這樣的:

for (String letter : letters) { 
    String currentSequence = start + letter; 
    System.out.println(currentSequence); // do something with your data here 
    if (depth > 0) { 
     printCombinations(currentSequence, depth - 1); 
    } 
} 
0

This方法似乎能夠採取一組,並創建像你正在尋找的組合。您需要將該類添加到項目中才能創建CombinationGenerator()。

似乎並不是唯一的方法,但至少您可以複製所使用的方法並調用它。

String[] letters; 
int[] indices; 
CombinationGenerator x = new CombinationGenerator (letters.length, 3); 
StringBuffer combination; 
while (x.hasMore()) { 
    combination = new StringBuffer(); 
    indices = x.getNext(); 
    for (int i = 0; i < indices.length; i++) { 
    combination.append (elements[indices[i]]); 
    } 
    System.out.println (combination.toString()); 
} 
0

遞歸救援!

static List<String> permutations(int len, String[] letters) { 
    List<String> ret = new ArrayList<String>(); 

    if (len == 1) { 
     ret.addAll(Arrays.asList(letters)); 
    } else { 
     List<String> perms = permutations(len - 1, letters); 
     for (String l : letters) { 
      ret.add(l); 
      for (String s : perms) { 
       ret.add(l + s); 
      } 
     } 
    } 

    return ret; 
} 

更新:我調整了代碼,也產生1n-1字符排列。

請注意,輸出的排列方式與OP指定的方式不同。我不希望它重要,但誰知道...

輸出示例:

[0, 00, 000, 001, 002, 003, 004, 005, 006, 007, 008, 009, 01, 010, 011, ...]