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

前端 未结 30 2233
逝去的感伤
逝去的感伤 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:45

    public class Permutation {
    
        //display all combination attached to a 3 digit number
    
        public static void main(String ar[]){
    
                char data[][]= new char[][]{{'a','k','u'},
                                    {'b','l','v'},
                                    {'c','m','w'},
                                    {'d','n','x'},
                                    {'e','o','y'},
                                    {'f','p','z'},
                                    {'g','q','0'},
                                    {'h','r','0'},
                                    {'i','s','0'},
                                    {'j','t','0'}};
    
    
            int num1, num2, num3=0;
            char tempdata[][]= new char[3][3];
            StringBuilder number = new StringBuilder("324"); // a 3 digit number
    
            //copy data to a tempdata array-------------------
            num1= Integer.parseInt(number.substring(0,1));
            tempdata[0] = data[num1];
            num2= Integer.parseInt(number.substring(1,2));
            tempdata[1] = data[num2];
            num3= Integer.parseInt(number.substring(2,3));
            tempdata[2] = data[num3];
    
            //display all combinations--------------------
            char temp2[][]=tempdata;
            char tempd, tempd2;
            int i,i2, i3=0;
            for(i=0;i<3;i++){
                    tempd = temp2[0][i];
                 for (i2=0;i2<3;i2++){
                     tempd2 = temp2[1][i2];
                     for(i3=0;i3<3;i3++){
                         System.out.print(tempd);
                         System.out.print(tempd2);
                         System.out.print(temp2[2][i3]);
                         System.out.println();
                     }//for i3
    
                }//for i2
             }
        }
    
    }//end of class
    

提交回复
热议问题