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

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

    In Java using recursion:

    import java.util.LinkedList;
    import java.util.List;
    
    public class Main {  
        // Number-to-letter mappings in order from zero to nine
        public static String mappings[][] = {
            {"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 generateCombosHelper(List combos, 
                String prefix, String remaining) {
            // The current digit we are working with
            int digit = Integer.parseInt(remaining.substring(0, 1));
    
            if (remaining.length() == 1) {
                // We have reached the last digit in the phone number, so add 
                // all possible prefix-digit combinations to the list
                for (int i = 0; i < mappings[digit].length; i++) {
                    combos.add(prefix + mappings[digit][i]);
                }
            } else {
                // Recursively call this method with each possible new 
                // prefix and the remaining part of the phone number.
                for (int i = 0; i < mappings[digit].length; i++) {
                    generateCombosHelper(combos, prefix + mappings[digit][i], 
                            remaining.substring(1));
                }
            }
        }
    
        public static List generateCombos(String phoneNumber) {
            // This will hold the final list of combinations
            List combos = new LinkedList();
    
            // Call the helper method with an empty prefix and the entire 
            // phone number as the remaining part.
            generateCombosHelper(combos, "", phoneNumber);
    
            return combos;
        }
    
        public static void main(String[] args) {
            String phone = "3456789";
            List combos = generateCombos(phone);
    
            for (String s : combos) {
                System.out.println(s);
            }
        }
    }
    

提交回复
热议问题