无法理解字符串置换Java代码 [英] Not able to understand string permutation Java code

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

问题描述

我有这个工作代码来打印字符串置换而没有重复,但是我无法完全理解它在逻辑上的工作方式.任何建议都会很有帮助.

I have this working code to print string permutations without repetitions, but not able to wrap my head around how is it working as in logic. Any suggestions will be really helpful.

private static void permutation(String input, String sofar) {
        if (input.equals("")) {
            System.out.println(count + " " + sofar);
            count++;
        }
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (input.indexOf(c, i + 1) != -1)
                continue;
            permutation(input.substring(0, i) + input.substring(i + 1), sofar+c);
        }
    }

函数调用:

String input = "ABBCD";
permutation(input, "");

推荐答案

 for (int i = 0; i < input.length(); i++) {

上面的for循环很神奇

The above for loop is doing the magic

输入ABCD

迭代

输入:BCD使用者:A ....递归继续

input: BCD sofar: A .... recursion goes on

输入:ACD使用者:B ....

input: ACD sofar: B ....

输入:ABD使用者:C ....

input: ABD sofar: C ....

输入:ABC沙发:D .....

input: ABC sofar: D .....

希望这会有所帮助

这篇关于无法理解字符串置换Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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