面试题:五笔的编码范围是a到y的25个字母,从1位到4位的编码,
如果将五笔的编码按字典序排序,形成数组如下:a, aa, aaa, aaaa, aaab, aaac, …, b, ba, baa, baaa, baab…yyyx, yyyy
其中a的索引是0,aa的索引是1,aaa的索引是2,aaaa的索引是3,以此类推:
1)、编写一个函数,输入是任意一个合法的字符串,输出这个字符串对应的索引;
2)、编写一个函数,输入是任意一个合法的索引,输出这个索引对应的字符串。
代码实现:
using System;
namespace cchoop
{
class Program
{
public static void Main()
{
Console.WriteLine(GetWubiIndexByStr("a"));
Console.WriteLine(GetWubiIndexByStr("aa"));
Console.WriteLine(GetWubiIndexByStr("aaa"));
Console.WriteLine(GetWubiIndexByStr("aaaa"));
Console.WriteLine(GetWubiIndexByStr("aaab"));
Console.WriteLine(GetWubiIndexByStr("b"));
Console.WriteLine(GetWubiStrByIndex(0));
Console.WriteLine(GetWubiStrByIndex(1));
Console.WriteLine(GetWubiStrByIndex(2));
Console.WriteLine(GetWubiStrByIndex(3));
Console.WriteLine(GetWubiStrByIndex(4));
Console.WriteLine(GetWubiStrByIndex(9));
}
public static int GetWubiIndexByStr(string wubiStr)
{
//权重
int[] factor = new int[] { 1 + 25 + 25 * 25 + 25 * 25 * 25, 1 + 25 + 25 * 25, 1 + 25, 1 };
int index = wubiStr.Length - 1;
for (int i = 0; i < wubiStr.Length; i++)
{
index += factor[i] * (wubiStr[i] - 'a');
}
return index;
}
public static string GetWubiStrByIndex(int index)
{
//权重
int[] factor = new int[] { 1 + 25 + 25 * 25 + 25 * 25 * 25, 1 + 25 + 25 * 25, 1 + 25, 1 };
char[] arr = new char[4];
int i = 0;
while (index > 0)
{
arr[i] = (char)('a' + index / factor[i]);
index = index % factor[i];
index--;
i++;
}
return new string(arr).TrimEnd();
}
}
}