C# solution with comment explanation (beats 89.82%)


  • 0
    K
    public class Solution {
        public IList<string> LetterCombinations(string digits) {
            
            IList<string> list = new List<string>();
            IList<string> list2 = new List<string>();
            IList<string> s1 = new List<string>();
            string first = String.Empty;
            string next = String.Empty;
            int digitIndex = 0;
            string[] letters = new string[] {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
            
            if (digits.Length ==0) return list;
            
            //first we form the first string list from the first digit i.e if digit is 2 then the list consists of "a","b","c"
            digitIndex = (int)Char.GetNumericValue(digits[0]) - 2;
            first = letters[digitIndex];
            for (int i=0;i<first.Length;i++)
                s1.Add(first[i].ToString());
            if (digits.Length ==1) return s1;
           
            //next we take the second digit's letter list and form the combination list with the first list, 
            //then we take the third digit and match every letter of it with the list formed in the previous step, and so on so forth..
            list = s1;
            for (int i=1;i<digits.Length;i++) {
                digitIndex = (int)Char.GetNumericValue(digits[i]) - 2;
                next = letters[digitIndex];
                for (int j=0;j<next.Length;j++)
                    list2.Add(next[j].ToString());
                list = FormStrings(list,list2);
                list2.Clear();
            }
            return list;
            
        }
        //concatenates the strings of the first list with the second's.
        //(in this problem, s2 consists of 3 one character-strings like "a","b","c")
        public IList<string> FormStrings(IList<string> s1,IList<string> s2)
        {
            IList<string> list = new List<string>();
            for (int i=0;i<s1.Count;i++) {
                for (int j=0;j<s2.Count;j++)
                    list.Add(s1[i]+""+s2[j]);
            }
            return list;
        }
    }
    

Log in to reply
 

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