题目描述:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
案例:
解决方案:
代码:
public IList<string> LetterCombinations(string str) {
List<string> strs = new List<string>();
if(str == "" || str == "1") return strs;
Dictionary<char, string> dic = new Dictionary<char, string>();
dic.Add('2', "abc");
dic.Add('3', "def");
dic.Add('4', "ghi");
dic.Add('5', "jkl");
dic.Add('6', "mno");
dic.Add('7', "pqrs");
dic.Add('8', "tuv");
dic.Add('9', "wxyz");
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '1') continue;
if (strs.Count <= 0)
{
for (int zfc = 0; zfc < dic[str[i]].Length; zfc++)
{
strs.Add(dic[str[i]].ToString()[zfc].ToString());
}
}
else
{
strs = StrMatch(strs, dic[str[i]]);
}
}
return strs;
}
public List<string> StrMatch(List<string> strs,string str)
{
List<string> arr = new List<string>();
for (int i = 0; i < strs.Count; i++)
{
for (int j = 0; j < str.Length; j++)
{
arr.Add(strs[i] + str[j]);
}
}
return arr;
}