2017-07-18 81 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非常感谢!!它的工作原理 –

相关问题