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

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

    static final String[] keypad = {"", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};
    
    
    
    String[] printAlphabet(int num){
            if (num >= 0 && num < 10){
                String[] retStr;
                if (num == 0 || num ==1){
                    retStr = new String[]{""};
                } else {
                    retStr = new String[keypad[num].length()];
                    for (int i = 0 ; i < keypad[num].length(); i++){
                        retStr[i] = String.valueOf(keypad[num].charAt(i));
                    }
                }
                return retStr;
            }
    
            String[] nxtStr = printAlphabet(num/10);
    
            int digit = num % 10;
    
            String[] curStr = null;
            if(digit == 0 || digit == 1){
                curStr = new String[]{""};
            } else {
                curStr = new String[keypad[digit].length()];
                for (int i = 0; i < keypad[digit].length(); i++){
                    curStr[i] = String.valueOf(keypad[digit].charAt(i));
                }
            }
    
            String[] result = new String[curStr.length * nxtStr.length];
            int k=0;
    
            for (String cStr : curStr){
                for (String nStr : nxtStr){
                    result[k++] = nStr + cStr;
                }
            }
            return result;
        }
    

提交回复
热议问题