Given a string of integers find out all the possible words that can made out of it in continuous order. [closed]

走远了吗. 提交于 2019-12-02 14:40:44

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!