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

谁说胖子不能爱 提交于 2019-12-31 07:42:18

问题


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


来源:https://stackoverflow.com/questions/32327170/given-a-string-of-integers-find-out-all-the-possible-words-that-can-made-out-of

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