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

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.

 

 1         public static List<string> LetterCombinationsofaPhoneNumber(string digits)
 2         {
 3             List<string>[] ret = new List<string>[]
 4                 {
 5                     new List<string>(),
 6                     new List<string>()
 7                 };
 8             if (digits.Length == 0)
 9                 return ret[0];
10 
11             //mapping of digit to letters
12             Dictionary<char, string[]> map = new Dictionary<char, string[]>();
13             map.Add('2', new string[]{"a", "b", "c"});
14             map.Add('3', new string[]{"d", "e", "f"});
15             map.Add('4', new string[]{"g", "h", "i"});
16             map.Add('5', new string[]{"j", "k", "l"});
17             map.Add('6', new string[]{"m", "n", "o"});
18             map.Add('7', new string[]{"p", "q", "r", "s"});
19             map.Add('8', new string[]{"t", "u", "v"});
20             map.Add('9', new string[]{"w", "x", "y", "z"});
21 
22             int curr_index = 0;
23             int new_index = 1;
24             //set up the first List<string>
25             foreach (var newchar in map[digits[0]])
26             {
27                 ret[curr_index].Add(newchar);
28             }
29             
30             //loop the rest of digits
31             for (int i = 1; i < digits.Length; i++)
32             {
33                 //construct next List<string> with current List<string> and current digit
34                 foreach (var pre in ret[curr_index])
35                 {
36                     foreach (var newchar in map[digits[i]])
37                     {
38                         ret[new_index].Add(pre + newchar);
39                     }
40                 }
41 
42                 ret[curr_index].Clear();
43                 curr_index = new_index;
44                 new_index = (new_index + 1) % 2;
45             }
46 
47             return ret[curr_index];
48         }

代码分析:

  建立两个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;

posted @ 2012-09-20 03:29  ETCOW  阅读(448)  评论(0编辑  收藏  举报