Android - 所有可能的字符排列匹配字符串? [重述]

时间:2014-07-23 11:28:25

标签: java android algorithm permutation

上次我问这个问题但是它被删除了,我被要求更准确地说明。 (请注意,此算法在我的加密应用程序中有一项非常重要的任务,但为了使其更简单,我使用了程序密码示例。)

将程序的密码视为abc123。它已锁定,我们必须将其解锁。考虑一下我们不知道。现在我必须编写一个程序来完成所有可能的字符排列,直到我获得密码并解锁程序。

例如,它必须首先通过az然后0-9然后它将开始所有可能的2个字符排列 - aa,ab,ac然后a1,a2,a3然后ba,bb,bc等它将继续直到z9 。然后它将经历所有三个字符可能的排列。这将持续到程序达到abc123。

即使创建了很多循环也没有用,因为我们实际上并不知道密码有多长。

1 个答案:

答案 0 :(得分:1)

使用递归方法调用。对于3个字母的字符串,您需要迭代最后一个索引上的所有可能字符。然后你想要在最后一个最后一个索引等等上迭代所有可能的字符。牢记这一点

private static List<Character> all = new ArrayList<Character>(); //your own collection chars
private static final int MAX_LENGTH = 10; //max password length
static {
    // add '0' to '9' and 'A' to 'Z' here in the same manner. 
    for (int i = 'a'; i <= 'z'; i++) 
        all.add((char)i);
}

public void go() {
    for (int i = 1; i <= MAX_LENGTH; i++)
        inputWordsWithLength(i);
}

// entrypoint for a word with a certain length
private void inputWordsWithLength(int wordlength) {
    char[] word = new char[wordlength];
    start(word);
    doForRange(word, 0, wordlength - 1);
}

// this method is responsible for character mutation on only one index,
// and recursively calls itself
private void doForRange(char[] word, int index, int lastindex) {
    for (char c : all) {
        word[index] = c;
        for (int i = index + 1; i <= lastindex; i++) {
            doForRange(word, i, lastindex);
        }
        inputWordIntoGUI(word);
    }
}

// inject the word into your GUI
private void inputWordIntoGUI(char[] word) {
    //implement this yourself.
}

// set the value on 'aaa', for example. Not necessary, but failsafe.
private void start(char[] word) {
    for (int i = 0; i < word.Length; i++)
        word[i] = all[0];
}

这只是一种可能性,但还有其他方法,在提出问题之前你必须先了解你真正想做的事情,因为/ a解决方案很容易找到。