2017-07-18 80 views
-3

我正在開發電子商務應用程序,我需要從給定的字符串中生成所有可能的單詞。從給定的字符串形成所有可能的單詞


輸入字符串:{AB}
預期輸出:A,AB,BA,B

截至目前,我發現了輸出爲:一個,ab,b
我正面臨問題,而從結尾回溯生成字符串ba

package com.ecommerce.util; 

import java.util.HashSet; 

public class Combinations { 
    private StringBuilder output = new StringBuilder(); 
    private final String inputstring; 

    public Combinations(final String str) { 
     inputstring = str; 
     System.out.println("The input string is : " + inputstring); 
    } 
    public HashSet<String> combine() { 
     HashSet<String >set=new HashSet<>(); 
     combine(0,set); 
     System.out.println(set); 
     return set; 
    } 

    private void combine(int start,HashSet<String >set) { 
     for (int i = start; i < inputstring.length(); ++i) { 
      output.append(inputstring.charAt(i)); 
      System.out.println(output); 
      set.add(output.toString()); 
      if (i < inputstring.length()) 
       combine`enter code here`(i + 1,set); 
      output.setLength(output.length() - 1); 
     } 
    } 
} 

在此先感謝您的幫助。

+2

這不是一個代碼寫作服務。發佈您到目前爲止所嘗試的內容,並向我們詢問有關您的嘗試的具體問題。 – Malphrush

+0

首先你必須計算給定字符串的所有組合,然後對於每個組合,你必須找出所有的排列組合。 –

+0

@Malphrush:我附上了代碼片段。 –

回答

1

您搜索的內容與所謂的功率集非常相似。在{a, b}的示例中,這是集合{{}, {a}, {b}, {a, b}}。有簡單的算法來計算它,可以在這裏找到SO Obtaining a powerset of a set in Java

您還可以找到在維基百科的描述和僞代碼:Power set at Wikipedia


注意,發電機組將被定義也包含空集{},你可以從得到的結果。減去它通過鏈接的算法(或在創建時直接拒絕它)。

它也不會關心元素的順序(即如何設置作品的定義),如果你想獲得abba你可以使用置換方法上powerSet方法的輸出這創建了每個元素的特徵的所有排列。這也已經在SO回答,比如這裏:Generating all permutations of a given string


無需修改就可以使用鏈接的方法powerSet(Set<T> originalSet)其通過使用代碼片段返回Set<Set<T>>permutation(String str)

String input = ... // Your input here 

// Convert the input into a set of character 
final Set<Character> inputSet = new HashSet<>(); 
for (int i = 0; i < input.length(); i++) { 
    inputSet.add(input.charAt(i)); 
} 

// Use the method to compute the power set 
Set<Set<Character>> powerSet = powerSet(inputSet); 

// Output all elements 
for (Set<Character> element : powerSet) { 
    // Combine the character in the set to a String 
    StringBuilder sb = new StringBuilder(); 
    for (Character c : element) { 
     sb.append(c); 
    } 

    // Here is a final element ready for collection or a print 
    String outputElement = sb.toString(); 
    // The method already prints the results by itself, you can modify it easily such that it returns a Set<String> or similar 
    permutation(outputElement); 
} 
+0

@Zabuba非常感謝!!它的工作原理 –

相關問題