Given a string of integers find out all the possib

2019-03-07 09:08发布

问题:

Given a string of integers how to find out all the possible words that can made out of it in continuous order. Eg: 11112

ans: AAAAB AKAB AAKB AAAL etc.

public static void main(String[] args) {
    String str="11111124";
    char strChar[]=str.toCharArray();
    String target="";
    for(int i=0;i<strChar.length;i++)
    {
        target=target+(char)Integer.parseInt(""+(16+strChar[i]));
    }
    System.out.println(target);
}

i am trying to find the solution for this but not able to find all combination

回答1:

Combining the comments saying that 163 can be 1,6,3 or 16,3, but not 1,63, and user3437460's suggestion of using recursion:

  1. Take first digit and convert to letter. Make recursive call using letter and remaining digits.
  2. Take first two digits. If <=26, convert to letter and make recursive call using letter and remaining digits.

Here is the code. Since I have no clue what to call the method, I'm going with x.

public static void main(String[] args) {
    x("11112", "");
    System.out.println("------");
    x("163", "");
}
private static final void x(String digits, String word) {
    if (digits.isEmpty())
        System.out.println(word);
    else {
        int num = Integer.parseInt(digits.substring(0, 1));
        x(digits.substring(1), word + (char)('A' + num - 1));
        if (digits.length() >= 2 && (num = Integer.parseInt(digits.substring(0, 2))) <= 26)
            x(digits.substring(2), word + (char)('A' + num - 1));
    }
}

Output

AAAAB
AAAL
AAKB
AKAB
AKL
KAAB
KAL
KKB
------
AFC
PC