这是一个队列的经典例子!
原题
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.
Example1:
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Example1:
Input: “12”
Output: “1a” “1b” “1c”
代码实现
public List<string> LetterCombinations(string digits)
{
if (digits.Trim() == string.Empty) return new List<string>();
Queue<string> q = new Queue<string>();
string[] mapping = { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
q.Enqueue("");
for (int i = 0; i < digits.Length; i++)
{
int x = digits[i] - 48;
while (q.Peek().Length == i)
{
string t = q.Dequeue();
foreach (var ch in mapping[x])
{
q.Enqueue(t + ch);
}
}
}
return q.ToList();
}
结果模拟
Input: “234”
结果:
绿色的为最后留在队列中的List。
题库
Leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp