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

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

    It is similar to a question called letter combinations of a phone number, here is my solution.
    It works for an arbitrary number of digits, so long as the result doesn't exceed the memory limit.

    import java.util.HashMap;
    public class Solution {
        public ArrayList letterCombinations(String digits) {
            ArrayList res = new ArrayList();
            ArrayList preres = new ArrayList();
            res.add("");
    
            for(int i = 0; i < digits.length(); i++) {
                String letters = map.get(digits.charAt(i));
                if (letters.length() == 0)
                    continue;
                for(String str : res) {
                    for(int j = 0; j < letters.length(); j++)
                        preres.add(str + letters.charAt(j));
                }
                res = preres;
                preres = new ArrayList();
            }      
            return res;
        }
    
        static final HashMap map = new HashMap(){{
            put('1', "");
            put('2',"abc");
            put('3',"def");
            put('4',"ghi");
            put('5',"jkl");
            put('6',"mno");
            put('7',"pqrs");
            put('8',"tuv");
            put('9',"wxyz");
            put('0', "");
        }} ;
    }
    

    I'm not sure how 12-digit international numbers affect the design.

    Edit: International numbers will also be handled

提交回复
热议问题