我是 C# 新手,正在尝试找出如何计算字符串中重复项的数量。输入和输出示例如下:
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice
Run Code Online (Sandbox Code Playgroud)
到目前为止我的代码如下:
using System;
using System.Collections;
using System.Linq;
public class Kata
{
public static int DuplicateCount(string str)
{
Stack checkedChars = new Stack();
Stack dupChars = new Stack();
str = str.ToLower();
for (int i=1; i < str.Length; i++) {
var alreadyCounted = checkedChars.Contains(str[i]) && dupChars.Contains(str[i]);
if (!checkedChars.Contains(str[i])) {
checkedChars.Push(str[i]);
} else if (checkedChars.Contains(str[i])) {
dupChars.Push(str[i]);
} else if (alreadyCounted) {
break;
}
}
return dupChars.Count;
}
}
Run Code Online (Sandbox Code Playgroud)
我的方法是循环遍历字符串中的每个字符。如果以前没有见过,请将其添加到“checkedChars”堆栈中(以跟踪它)。如果已经计数,则将其添加到“dupChars”堆栈中。然而,这没有通过测试。例如:
aabbcde是字符串,测试失败并显示:Expected: 2 But Was: 1
另外,当我控制台出错误时,checkedChars 堆栈似乎是空的。
谁能发现我哪里出了问题吗?
小智 5
我建议您改用 LINQ。它是一个更适合解决该问题的工具,并且可以生成更清晰的代码:
class Program
{
static void Main(string[] args)
{
var word = "indivisibility";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
word = "Indivisibilities";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
word = "aA11";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
word = "ABBA";
Console.WriteLine($"{word} has {CountDuplicates(word)} duplicates.");
Console.ReadLine();
}
public static int CountDuplicates(string str) =>
(from c in str.ToLower()
group c by c
into grp
where grp.Count() > 1
select grp.Key).Count();
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
indivisibility has 1 duplicates.
Indivisibilities has 2 duplicates.
aA11 has 2 duplicates.
ABBA has 2 duplicates.
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。