-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinationsOfPhoneNumber.cs
More file actions
55 lines (46 loc) · 1.83 KB
/
LetterCombinationsOfPhoneNumber.cs
File metadata and controls
55 lines (46 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
namespace CodeChallenge
{
public class LetterCombinationsOfPhoneNumber
{
// Created a mapping of digits to letters as a dictionary.
public static readonly Dictionary<char, string> phoneMap = new Dictionary<char, string>
{
{ '2', "abc" }, { '3', "def" },
{ '4', "ghi" }, { '5', "jkl" },
{ '6', "mno" }, { '7', "pqrs" },
{ '8', "tuv" }, { '9', "wxyz" }
};
public IList<string> LetterCombinations(string digits)
{
//Handle cases where input is empty.
if (string.IsNullOrEmpty(digits))
{
return new List<string>();
}
//Defining a list to hold the results
List<string> results = new List<string>();
//Call the recursive function to start building combinations.
GenerateCombinations(0, digits, "", results);
return results;
}
// Recursive helper function to generate combinations.
private void GenerateCombinations(int index, string digits, string currentCombination, List<string> results)
{
//If the current combination length equals digits length, add to results.
if (index == digits.Length)
{
results.Add(currentCombination);
return;
}
// Get the letters mapped to the current digit.
char digit = digits[index];
string letters = phoneMap[digit];
//Loop through each letter mapped to this digit.
foreach (char letter in letters)
{
//Move to the next digit, add the current letter to the combination.
GenerateCombinations(index + 1, digits, currentCombination + letter, results);
}
}
}
}