键盘组合电话号码

时间:2016-01-26 12:14:28

标签: java combinations permutation

我知道这个问题已被问过一百次,但我正在寻找一个不涉及任何字符串函数或外部类的解决方案。

我编写了一些实际可行的类,但它们都使用了String.substring或String.replace,Arraylists等,这在我的情况下是不允许的。

我已经在这上面待了一个多星期了,我似乎无法取得任何进展。

我只是不能将String方法放在一个非常大的循环中。

有什么想法吗?

这是我到目前为止所写的内容。

public class Oldie {
    public static void main(String[] args) {
        char[][] array = {
            { '0' }, { '1' }, { 'A', 'B', 'C' }, { 'D', 'E', 'F' },
            { 'G', 'H', 'I' }, { 'J', 'K', 'L' }, { 'M', 'N', 'O' },
            { 'P', 'Q', 'R', 'S' }, { 'T', 'U', 'V' }, { 'W', 'X', 'Y', 'Z' }
        };

        String num = "222";
        int[] number = new int[num.length()];
        char[] permutations = new char[num.length()];

        for (int i = 0; i < num.length(); i++) {
            number[i] = Character.getNumericValue(num.charAt(i));
        }

        char First, Second, Third;

        for (char i = array[number[0]][0]; i <= array[number[0]][array[number[0]].length - 1]; i++) {
            First = i;

            for (char j = array[number[1]][0]; j <= array[number[1]][array[number[1]].length - 1]; j++) {
                Second = j;

                for (char k = array[number[2]][0]; k <= array[number[2]][array[number[2]].length - 1]; k++) {
                    Third = k;

                    System.out.println("" + First + "" + Second + "" + Third);
                }
            }
        }
    }
}

如果我可以在带有redix等的基本类型解决方案中做到这一点会更好。

5 个答案:

答案 0 :(得分:1)

我不太确定,你的循环是什么意思,但是当你修复它时,这应该是另一个解决方案,而不保存字符串(现在这会引发“java.lang.ArrayIndexOutOfBoundsException”,因为我不理解,你想要用你的for循环完成什么。这段代码应该更多地被视为一个提示如何解决您的问题,而不是完整的解决方案!这也有点节省旧字符串。相反,您也可以删除每个for循环结束时字符串的最后一个字符:

public class Oldie {
    char[][] array = {
            { '0' }, { '1' }, { 'A', 'B', 'C' }, { 'D', 'E', 'F' },
            { 'G', 'H', 'I' }, { 'J', 'K', 'L' }, { 'M', 'N', 'O' },
            { 'P', 'Q', 'R', 'S' }, { 'T', 'U', 'V' }, { 'W', 'X', 'Y', 'Z' }
        };
    String num = "222";
    String savedPerm;
    int[] number = new int[num.length()];

    public static void main(String[] args) {
        Oldie oldie = new Oldie();
        oldie.givePerm(0);
    }

    Oldie(){
        for (int i = 0; i < num.length(); i++) {
            number[i] = Character.getNumericValue(num.charAt(i));
        }
    }

    private void givePerm(int position){
        String oldSavedPerm=savedPerm;
//      if(array.length!=number.length){
//          System.out.println("Different length!");
//          System.out.println(array.length+";"+number.length);
//          return;
//      }
        for (char c = array[number[position]][0]; c <= array[number[position]][array[number[position]].length - 1]; c++) {
            savedPerm=c+oldSavedPerm;
            if(position<array.length-1)
                givePerm(position+1);
            else
                System.out.println(savedPerm);
        }
    }
}

答案 1 :(得分:1)

以下是我解决问题的方法。

char[][] array = {
    { '0' }, { '1' }, { 'A', 'B', 'C' }, { 'D', 'E', 'F' },
    { 'G', 'H', 'I' }, { 'J', 'K', 'L' }, { 'M', 'N', 'O' },
    { 'P', 'Q', 'R', 'S' }, { 'T', 'U', 'V' }, { 'W', 'X', 'Y', 'Z' }
};
String num = "123";

// creates an combination Array
// for 123 this is {{1},{ABC},{DEF}}
char[][] combinationArr = new char[num.length()][];         
for(int ix = 0; ix < num.length(); ix++)
    combinationArr[ix] = array[Character.getNumericValue(num.charAt(ix))];

// now print all permutations of combination Array
// ics holds the actual index at each position
int[] ics = new int[num.length()];
boolean end = false;
while(!end){ // while there are combinations left       
    // print the actual combination
    for(int i = 0; i < combinationArr.length; i++)
        System.out.print(combinationArr[i][ics[i]]);
    System.out.println();               
    // increases one index, starting with the last one.
    // If there is no char left it starts again at 0
    // and the index before will get increased.
    // If the first one could not get increased
    // we have all combinations.
    for(int i = ics.length - 1; i >= 0; i--){
        ics[i]++;
        if(ics[i] == combinationArr[i].length)
            if(i == 0) end = true;
            else ics[i] = 0;
        else break;
    }               
}

答案 2 :(得分:1)

这实际上对我有用!!感谢ctst!

public class Oldie {
private static char[][] array = { { '0' }, { '1' }, { 'A', 'B', 'C' }, { 'D', 'E', 'F' },
        { 'G', 'H', 'I' }, { 'J', 'K', 'L' }, { 'M', 'N', 'O' },
        { 'P', 'Q', 'R', 'S' }, { 'T', 'U', 'V' }, { 'W', 'X', 'Y', 'Z' } };
private static String num = "2222";
private static char[] savedPerm = new char[num.length];
private static int[] number = new int[num.length()];

public static void main(String[] args) {

    for (int i = 0; i < num.length(); i++) {
        number[i] = Character.getNumericValue(num.charAt(i));
    }
    givePerm(0);
}


private static void givePerm(int position) {
    for (char c = array[number[position]][0]; c <= array[number[position]][array[number[position]].length - 1]; c++) {
        savedPerm[position] = c;
        if (position < number.length - 1)
            givePerm(position + 1);
        else{
            for(char text: savedPerm){
                 System.out.print(""+text);
            }
            System.out.println();
        }
    }
}
}

答案 3 :(得分:0)

我建议你做一个递归方法:

private String givePerm(String givenPerm, char[][] array, int position, int[] number){
    if(array.length!=number.length)
        return null;
    for (char c = array[number[position]][0]; c <= array[number[position]][array[number[position]].length - 1]; c++) {
        String permString;
        if(position<array.length-1)
             permString = givePerm(c+givenPerm, array, position+1);
        else
             permString = ""+c; 
        return permString;
     }
}

答案 4 :(得分:0)

使用递归,您可以调用permutations方法并继续减少输入数字的数量,方法是抓住头部数字并将尾部传递给下一个呼叫。

public class Oldie {
    private static final char[][] KEYS = {
        { '0' },
        { '1' },             { 'A','B','C' }, { 'D','E','F' },
        { 'G','H','I' },     { 'J','K','L' }, { 'M','N','O' },
        { 'P','Q','R','S' }, { 'T','U','V' }, { 'W','X','Y','Z' }
    };

    public static void main(String[] args) {
        try {
            permutations("222");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    public static void permutations(String inputNumber) throws IllegalArgumentException {
        permutations(toDigitArray(inputNumber), "");
    }

    private static void permutations(int[] inputDigits, String outputLetters) throws IllegalArgumentException {
        int headDigit = inputDigits[0];
        int[] tailDigits = tail(inputDigits);
        char[] letters = KEYS[headDigit];

        for (int i = 0; i < letters.length; i++) {
            char letter = letters[i];
            String result = outputLetters + letter;

            if (tailDigits.length == 0) {
                System.out.println(result);
            } else {
                permutations(tailDigits, result);
            }
        }
    }

    private static int[] toDigitArray(String str) throws IllegalArgumentException {
        return toDigitArray(str.toCharArray());
    }

    private static int[] toDigitArray(char[] arr) throws IllegalArgumentException {
        int[] intArr = new int[arr.length];

        for (int i = 0; i < intArr.length; i++) {
            if (!Character.isDigit(arr[i])) {
                throw new IllegalArgumentException("Character is not a valid digit");
            }

            intArr[i] = Character.digit(arr[i], 10);
        }

        return intArr;
    }

    private static int[] tail(int[] arr) {
        int[] dest = new int[arr.length - 1];
        System.arraycopy(arr, 1, dest, 0, dest.length);
        return dest;
    }
}

输出

AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC