How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2187
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

30条回答
  •  自闭症患者
    2020-12-22 18:51

    I rewrote the latest answer to this (referred above) , from C to Java. I also included the support for 0 and 1 (as 0 and 1) because numbers such as 555-5055 weren't working at all with the above code.

    Here it is. Some comments are preserved.

    public static void printPhoneWords(int[] number) {
        char[] output = new char[number.length];
        printWordsUtil(number,0,output);
    }
    
    static String[] phoneKeys= new String[]{"0", "1", "ABC", "DEF", "GHI", "JKL",
                   "MNO", "PQRS", "TUV", "WXYZ"};
    private static void printWordsUtil(int[] number, int curDigIndex, char[] output) {
        // Base case, if current output word is done
        if (curDigIndex == output.length) {
            System.out.print(String.valueOf(output) + " "); 
            return;
        }
    
          // Try all 3-4 possible characters for the current digit in number[]
          // and recurse for the remaining digits
    
        char curPhoneKey[] = phoneKeys[number[curDigIndex]].toCharArray();
        for (int i = 0; i< curPhoneKey.length ; i++) {
            output[curDigIndex] = curPhoneKey[i];
            printWordsUtil(number, curDigIndex+1, output);
            if (number[curDigIndex] <= 1) // for 0 or 1
                return;
        }
    }
    
    public static void main(String[] args) {
        int number[] = {2, 3, 4};
        printPhoneWords(number);
        System.out.println();
    }
    

提交回复
热议问题