String Permutations Java

时间:2012-09-25 20:21:42

标签: java algorithm permutation

我需要得到一个字符串的所有排列,但有一个扭曲。我需要获得排列,但需要不同的长度。 像这样: AB的排列将是:

A

AA

BB

AB

BA

我可以得到一个固定长度的字符串的排列,但我坚持这个。

3 个答案:

答案 0 :(得分:1)

public void processPermutations(String s) {
  for (int i=1; i<s.length; i++) {
    String substring = s.substring(0, i);
    // Generate and process the permutations of the substring here...
  }
}

答案 1 :(得分:0)

你可以这样做:

public List<String> getPermutations(String s) {
    List<String> result = new ArrayList<String>();

    if (s.length() > 1) {
        for (int i = 0; i < s.length(); i++) {
            //Create a string that has all the characters of s except the ith one
            String smallerString = s.substring(0,i) + s.substring(i + 1, s.length());
            result.addAll(getPermutations(smallerString));

            //Get permutations involving a single character appearing multiple times,
            //ie. AA, AAA, AAAA, etc.
            String repeatString = new String();
            for (int j = 1; j <= s.length(); j++) {
                repeatString = repeatString + s.charAt(i);
                result.add(repeatString);
            }
        }
    }

    //Add all the permutations using all the string's characters to the list here.
    return result;
}

尽量不要考虑那种复杂性;)

答案 2 :(得分:0)

您必须首先将字符串的组合放入到递减的桶数中,然后在每个组合桶上进行置换。例如,如果您的字符串有3个字符:

&#34; ABC&#34;的组合选择3 = 1 &#34; ABC&#34;的组合选择2 = 3 &#34; ABC&#34;的组合选择1 = 3

因此,您需要找到这7个案例中每个案例的排列。在伪代码中:

int lenString = s.length
int[] all_permutations = new array
for( buckets = 1 to lenString ){
    int[] c = Combinations( s, buckets )
    int[] p = Permutations( c )
    all_permutations += p   
}