某天下午忙的眼到爆,茶歇的时候突然聊起算法,同事提到写个9宫格键盘下的英文字符全排列。嗯。。。
第二天老哥发来了Python的递归实现,十分精简玄妙。
Challenge Accepted!
我来个循环的吧,直接上代码:
C#循环的实现using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var test = new Test();
test.Permutation("234");
test.Print();
}
static Dictionary<string,string> KeyMap = new Dictionary<string,string>{
{"2","abc"},
{"3","def"},
{"4","ghi"},
{"5","jkl"},
{"6","mno"},
{"7","pqrs"},
{"8","tuv"},
{"9","wxyz"},
};
string[] OutPut;
void Permutation(string input)
{
var repeatArr = new int[input.Length];
var inputArr = input.ToCharArray();
var numberOfCombination = 1;
for(int i = input.Length - 1; i >= 0 ; i--)
{
var str = KeyMap[inputArr[i].ToString()];
repeatArr[i] = numberOfCombination;
numberOfCombination = numberOfCombination * str.Length;
}
OutPut = new string[numberOfCombination];
for(int x = 0; x < input.Length; x++)
{
var letterPointer = 0;
var count = 0;
var letters = KeyMap[inputArr[x].ToString()];
for(int y = 0; y < numberOfCombination; y++)
{
var lettersArr = letters.ToCharArray();
var letter = lettersArr[letterPointer];
OutPut[y] += letter.ToString();
count++;
if(count == repeatArr[x])
{
count = 0;
letterPointer++;
if(letterPointer == lettersArr.Length)
{
letterPointer = 0;
}
}
}
}
}
void Print()
{
for(int i = 0; i < OutPut.Length; i++)
{
Console.WriteLine(OutPut[i]);
}
}
}
挑战达成!
过两天懒劲过了把解析补上嗯嗯,先立flag
网友评论