重排的字符串 [英] permute a string

查看:106
本文介绍了重排的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于字符串,打印其所有排列。要做到这一点,我想出了下面的程序。

Given the String, print all its permutations. To do that, i came up with the following program.

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,一切版画是

But, for the given input ABC, all it prints are

ABC
BAC

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

I cant seem to figure out what the problem is

推荐答案

想通了这个问题。问题是,在函数调用:

Figured out the problem. The problem was in the function invocation:

permuteStrings(inputString,I + 1,完成);

正确的做法应该是:

permuteStrings(inputString, start + 1, finish);

这篇关于重排的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆