我是C#的新手,我使用Javascript解决了该算法,任何人都可以帮助我将以下代码转换为C#。
详细信息:
给出一个单词数组和一个数字K,返回一个长度为K的数组,其中数组的第i个元素是其中长度为i的唯一前缀的数量给定的单词(i = 1,2,...,K)(仅包括至少有i个字符长)。
我的代码:
function getUniquePrefixCount(words, len) {
const prefixMap = {};
words.forEach(word => {
if (word.length >= len) {
const prefix = word.substr(0, len);
prefixMap[prefix] = true;
}
});
return Object.keys(prefixMap).length;
}
function getFrequentWordCount(words, k) {
return [...Array(k)].map(
(_, i) => getUniquePrefixCount(words, i + 1)
);
}
string[] words = new string[4] { "apple", "app", "apricot", "stone" };
int[] output = new int[8];
for (int i = 0; i < 8; i++)
{
output[i] = words.GroupBy(s => (s.Length >= i + 1 ? s.Substring(0, i + 1) : string.Empty))
.Select(x => new { x.Key, Count = x.Count() })
.Where(x => x.Key != string.Empty).Count();
Console.WriteLine(output[i]);
}