字符串的排列 [英] Permutations of a string

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

问题描述

public class Permute {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter a string");
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
        String text = bufReader.readLine();
        shuffle("",text);
    }
    public static void shuffle(String dummy, String input){
        if(input.length() <= 1)
            System.out.println(dummy+input);
        else{
            for(int i=0; i <input.length();i++){
                input = input.substring(i,1) + input.substring(0,i) + input.substring(i+1);
                shuffle(dummy+input.substring(0,1),input.substring(1));
            }           
        }
    }
}

Am尝试打印输入的字符串的所有排列。我真的无法猜到哪里出错了,因为在纸面上我发现这个正在执行。究竟出错了。

Am trying to print all the permutations of a string entered. And I really cannot guess where am going wrong because on paper I find that this executing. Where exactly am going wrong.

推荐答案

public class Permute {
    public static void main(String[] args) throws IOException {
        System.out.println("Enter a string");
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(System.in));
        String text = bufReader.readLine();
        shuffle("",text);
    }
    public static void shuffle(String dummy, String input){
        if(input.length() <= 1)
            System.out.println(dummy+input);
        else{
            for(int i=0; i <input.length();i++){
                input = input.substring(i,i+1) + input.substring(0,i) + input.substring(i+1);
                shuffle(dummy+input.substring(0,1),input.substring(1));
            }           
        }
    }
}

它应该是input.substring(i,i + 1)而不是input.substring(i,1)。因为每次我只需要1个字符是常量,这是在字符串的开头,而其他字符必须是混乱的。

It should be input.substring(i,i+1) instead of input.substring(i,1). Because each time I need only 1 character to be constant, which is at the beginning of the string and others have to be jumbled.

该错误是我认为substring的功能是substring(beginIndex,length)。但它是substring(beginIndex,endIndex)。

The bug was I presumed the functionality of substring to be substring(beginIndex, length). But it is substring(beginIndex,endIndex).

@Oli:谢谢你的帮助。

@Oli: Thank you for the help.

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

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