置换一个字符串

时间:2012-09-03 18:42:45

标签: java string algorithm permutation

给定String,打印所有排列。为此,我提出了以下计划。

public static char[] swap(char[] input, int i, int j) {
        char temp;
        temp = input[i];
        input[i] = input[j];
        input[j] = temp;

        return input;

    }

    /**
     * 
     * @param args
     */

    public static void permuteStrings(char[] inputString, int start, int finish ) {
        //Base case: When there is only single element, print the string
        if(start == finish) 
            System.out.println(inputString);
        else {
            //Recursive case: Swap first element with all the elements and permute on the 
                           // rest of string.
            for(int i = start; i <= finish; i++) {
                inputString = swap(inputString, start, i);
                permuteStrings(inputString, i + 1, finish);
                inputString = swap(inputString,start, i); //restoring the original string
            }
        }
    }

但是,对于给定的输入ABC,它打印的所有内容都是

ABC
BAC

我似乎无法弄清楚问题是什么

2 个答案:

答案 0 :(得分:1)

找出问题所在。问题出在函数调用中:

permuteStrings(inputString, i + 1, finish);

正确的方法是:

permuteStrings(inputString, start + 1, finish);

答案 1 :(得分:0)

使用递归

public static void permutation(String str) 
{ 
permutation("", str); 
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) 
 System.out.println(prefix);
else 
{
    for (int i = 0; i < n; i++)
     permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}