for循环到递归JAVA

时间:2016-05-08 20:10:58

标签: java recursion

我需要编写一个递归函数来发现给定长度的密码,允许的字符是a-z。我不允许使用循环,但我无法让它工作。

这里我的解决方案有一个for循环,我需要取消一些如何。

public static String findPassword(String p, int length) {
    String pass = "";
    return findPassword(p, length, pass);
}

private static String findPassword(String p, int length, String pass) {

    String abc = "abcdefghijklmnopqrstuvwxryz";

    if (pass.length() == length) {
        if (p.equals(pass))
            return pass;
        return "";
    }

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

        if (p.equals(findPassword(p, length, pass + abc.charAt(i))))
            return findPassword(p, length, pass + abc.charAt(i));
    }

    return "";
}

我曾尝试过任何我能想到的事情而且没有任何作用。

2 个答案:

答案 0 :(得分:0)

您可以尝试转换数字中的密码,然后使用recursione将p的值增加到转换后的密码的值:

public class Password {
    public static void main(String[] args) {
        System.out.println(findPassword(0, "this is the password to find"));
    }

    public static String findPassword(int p, final String passwordToFind) {
        System.out.println(p); //just checkin it's working
        if (p == passToInt(passwordToFind))
            return passwordToFind;
        else
            return findPassword(++p, passwordToFind);
    }

    private static int passToInt(String passwordToFind) {

        int a = 0;
        for (byte b : passwordToFind.getBytes()) {
            a += b;
        }
        return a;
    }
}

这不是世界上最漂亮的代码,我没有深入了解它是否真的有效,它只是让你知道如何在不使用循环的情况下解决它,而只是一个简单的递归

答案 1 :(得分:0)

public static void main(String[] args)
{
    System.out.println(findPassword("stack", 5));
}

private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";

public static String findPassword(String solution, int length)
{
    return findPassword(solution, length, "", 0);
}

private static String findPassword(String solution, int length, String pass, int alphabetIndex)
{
    if (pass.length() == length)
    {
        if (solution.equals(pass))
            return pass;
        return "";
    }

    if (alphabetIndex < alphabet.length())
    {
        String found = findPassword(solution, length, pass + alphabet.charAt(alphabetIndex), 0);

        if (found.length() == 0)
        {
            return findPassword(solution, length, pass, alphabetIndex + 1);
        }

        return found;
    }

    return "";
}

**你的abc String有多余的&#34; r&#34;留给char&#34; y&#34;。