查找给定单词的最频繁字符
Finding most frequent char for a given word
我想使用 System.Linq 来编写一个方法,该方法 returns 是字符串中第一个、最频繁出现的字符。
例如:"AABABBC" => 'A'。
如果两个字母出现相同,则应返回出现在字符串中的第一个字母。
下面的示例应该有效。但是,我试图找到一个更有效的解决方案,这并不意味着首先对字符进行排序。
我正在考虑使用 Enumerable.Aggregate() 来计算重复次数,同时也遍历单词。不知道该怎么做,虽然...
有任何想法吗?谢谢:)
public static char MostAparitionsChar(string word)
{
return word.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(g => g.Key)
.First();
}
我不知道 OrderByDescending 的确切实现,但我认为它不会比 O(n*log n) 快。但是找到最大值应该只是 O(n)。因此,如果不排序可以节省一些时间,但只查找最大值:
public static char MostAparitionsChar(string word)
{
char result = ' ';
int max = int.MinValue;
foreach(var grouping in word.GroupBy(x => x))
{
int count = grouping.Count();
if(count > max)
{
max = count;
result = grouping.Key;
}
}
return result;
}
我想使用 System.Linq 来编写一个方法,该方法 returns 是字符串中第一个、最频繁出现的字符。 例如:"AABABBC" => 'A'。 如果两个字母出现相同,则应返回出现在字符串中的第一个字母。
下面的示例应该有效。但是,我试图找到一个更有效的解决方案,这并不意味着首先对字符进行排序。 我正在考虑使用 Enumerable.Aggregate() 来计算重复次数,同时也遍历单词。不知道该怎么做,虽然... 有任何想法吗?谢谢:)
public static char MostAparitionsChar(string word)
{
return word.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Select(g => g.Key)
.First();
}
我不知道 OrderByDescending 的确切实现,但我认为它不会比 O(n*log n) 快。但是找到最大值应该只是 O(n)。因此,如果不排序可以节省一些时间,但只查找最大值:
public static char MostAparitionsChar(string word)
{
char result = ' ';
int max = int.MinValue;
foreach(var grouping in word.GroupBy(x => x))
{
int count = grouping.Count();
if(count > max)
{
max = count;
result = grouping.Key;
}
}
return result;
}