您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Letter Combinations of a Phone Number

2012-09-20 03:29 656 查看
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

public static List<string> LetterCombinationsofaPhoneNumber(string digits)
{
List<string>[] ret = new List<string>[]
{
new List<string>(),
new List<string>()
};
if (digits.Length == 0)
return ret[0];

//mapping of digit to letters
Dictionary<char, string[]> map = new Dictionary<char, string[]>();
map.Add('2', new string[]{"a", "b", "c"});
map.Add('3', new string[]{"d", "e", "f"});
map.Add('4', new string[]{"g", "h", "i"});
map.Add('5', new string[]{"j", "k", "l"});
map.Add('6', new string[]{"m", "n", "o"});
map.Add('7', new string[]{"p", "q", "r", "s"});
map.Add('8', new string[]{"t", "u", "v"});
map.Add('9', new string[]{"w", "x", "y", "z"});

int curr_index = 0;
int new_index = 1;
//set up the first List<string>
foreach (var newchar in map[digits[0]])
{
ret[curr_index].Add(newchar);
}

//loop the rest of digits
for (int i = 1; i < digits.Length; i++)
{
//construct next List<string> with current List<string> and current digit
foreach (var pre in ret[curr_index])
{
foreach (var newchar in map[digits[i]])
{
ret[new_index].Add(pre + newchar);
}
}

ret[curr_index].Clear();
curr_index = new_index;
new_index = (new_index + 1) % 2;
}

return ret[curr_index];
}


代码分析:

  建立两个List<string>,替换使用,通过前一个List<string>的每一个元素后面 + map[digit] 的每一个字母,产生后一个List<string>。

  例如: “49”

  List<string> 1 : g, h, i;

  List<string> 2 : gw, gx, gy, gz, hw, hx, hy, hz, iw, ix, iy, iz;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: