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

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

    This is the C# port of this answer.

    Code

    public class LetterCombinations
    {
        private static readonly Dictionary Representations = new Dictionary
        {
           {"2", "abc" },
           {"3", "def" },
           {"4", "ghi" },
           {"5", "jkl" },
           {"6", "mno" },
           {"7", "pqrs" },
           {"8", "tuv" },
           {"9", "wxyz" },
        };
    
        public static List FromPhoneNumber(string phoneNumber)
        {
            var result = new List { string.Empty };
    
            // go through each number in the phone
            for (int i = 0; i < phoneNumber.Length; i++)
            {
                var pre = new List();
                foreach (var str in result)
                {
                    var letters = Representations[phoneNumber[i].ToString()];
                    // go through each representation of the number
                    for (int j = 0; j < letters.Length; j++)
                    {
                        pre.Add(str + letters[j]);
                    }
                }
                result = pre;
            }
    
            return result;
        }
    }
    

    Unit Tests

    public class UnitTest
    {
        [TestMethod]
        public void One_Digit_Yields_Three_Representations()
        {
            var sut = "2";
    
            var expected = new List{ "a", "b", "c" };
            var actualResults = LetterCombinations.FromPhoneNumber(sut);
    
            CollectionAssert.AreEqual(expected, actualResults);
        }
    
        [TestMethod]
        public void Two_Digits_Yield_Nine_Representations()
        {
            var sut = "22";
    
            var expected = new List { "aa", "ab", "ac", "ba", "bb", "bc", "ca", "cb", "cc" };
            var actualResults = LetterCombinations.FromPhoneNumber(sut);
    
            CollectionAssert.AreEqual(expected, actualResults);
        }
    
        [TestMethod]
        public void Three_Digits_Yield_ThirtyNine_Representations()
        {
            var sut = "222";
    
            var actualResults = LetterCombinations.FromPhoneNumber(sut);
    
            var possibleCombinations = Math.Pow(3,3); //27
    
            Assert.AreEqual(possibleCombinations, actualResults.Count);
        }
    }
    

提交回复
热议问题