【LeetCode】C# 17、Letter Combinations of a Phone Number

来源:互联网 发布:工业机器人控制算法 编辑:程序博客网 时间:2024/06/14 07:48

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.

类似九宫格输入法,输入两个数字之后返回所有可能的字母组合。

思路:先把九宫格代表的字符放到一个数组中方便调用,然后就是遍历和添加了。
值得注意的是digits中的数字取出来的是字符,要先转为string再转为数字不然索引会出问题。

public class Solution {    public IList<string> LetterCombinations(string digits) {        IList<string> res = new List<string>();        string[] mapping = new string[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        if(digits == "") return res;        res.Add("");        for(int i=0;i<digits.Length;i++){            List<string> temp = new List<string>();            foreach(string item in res){                for(int j=0;j<mapping[Convert.ToInt32(digits[i].ToString())].Length;j++){                    string tempstring = item + mapping[Convert.ToInt32(digits[i].ToString())][j].ToString();                    temp.Add(tempstring);                }            }            res = temp;        }        return res;    }}
原创粉丝点击