My Solution in C#


  • 0
    P
    /// <summary>
            /// Method that return all possible letter combinations that the number could represent
            /// </summary>
            /// <param name="digits">input digits</param>
            /// <returns>list of all combination</returns>
            static public IList<string> LetterCombinations(string digits)
            {
                // list of the combinations of all the letters
                IList<string> conbinationList = new List<string>();
    
                // check for empty input string
                if (digits.Trim().Length == 0) return conbinationList;
    
                // check for invalid input string
                int n;
                if (!int.TryParse(digits, out n))
                {
                    Console.WriteLine("Invalid");
                    return null;
                }
    
                // Index from 0 to 9 as the number of the dial has the following values
                string[] dial = new string[10] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    
                int[] intDigits = new int[digits.Length];
                // store each number in the input as index of the dial
                for (int i = 0; i < digits.Length; i++)
                {
                    intDigits[i] = int.Parse(digits[i].ToString());
                }
    
                // using queue to store the combinations as they are building.
                Queue<string> strCombinations = new Queue<string>();
                // to run the loop first time. 
                string s = string.Empty;
                strCombinations.Enqueue(s);
    
                // for each number in the given dialas input string
                for (int i = 0; i < intDigits.Length; i++)
                {
                    int index = intDigits[i];
                    int count = strCombinations.Count;
    
                    for (int iteration = 0; iteration < count; iteration++)
                    {
                        s = strCombinations.Dequeue();
    
                        for (int k = 0; k < dial[index].Length; k++)
                        {
                            strCombinations.Enqueue(s + dial[index][k]);
                        }
                    }
                }
    
                // collect all the combinations in the list
                while (strCombinations.Count > 0)
                {
                    conbinationList.Add(strCombinations.Dequeue());
                }
    
                return conbinationList;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.