我正在尝试解决问题。
基本上,我需要从字符数组中选择第二个重复项。
Input {'x','y','z','x','y'} output: y
Input { 'a', 'a', 'b', 'a', 'c', 'b', 'a', 'c', 'b' } Output: b
Input { 'a','a','a','b','a','c','b','a','c','b' } output: b
编辑:
Input {'a', 'b', 'c', 'b', 'a', 'c', 'b', 'a', 'c', 'b'} Output: a
我已经尝试编写这段代码,但是如果第一个字符立即重复出现,它会失败:(有任何纠正的帮助吗?
public static char returnSecondDuplicate(char[] arr)
{
if (arr.Length == 0)
throw new ArgumentNullException("empty input");
var dictionary = new Dictionary<char, int>();
Char second = '\0';
int duplicateCount = 0;
for (int i = 0; i <= arr.Length - 1; i++)
{
if (!dictionary.ContainsKey(arr[i]))
{
dictionary.Add(arr[i], 1);
}
else
{
duplicateCount++;
if (duplicateCount == 2)
{
second = arr[i];
}
}
}
return second;
}
问题是您要计算的是重复的总数,而不是单个字符的重复数。
给出了一些linq答案,但是如果您想知道如何修复现有代码,则可以执行以下操作:
public static char returnSecondDuplicate(char[] arr)
{
if (arr.Length == 0)
throw new ArgumentNullException("Empty Array passed");
var dictionary = new Dictionary<char, int>();
char firstDuplicate = '\0';
for (int i = 0; i <= arr.Length - 1; i++)
{
if (!dictionary.ContainsKey(arr[i]))
{
dictionary.Add(arr[i], 1);
}
else if (firstDuplicate == '\0')
{
firstDuplicate = arr[i];
}
else if(arr[i] != firstDuplicate)
{
return arr[i];
}
}
return '\0'; //not found
}
基本上,您必须跟踪先复制哪个字母。有了第一个重复项后,请检查后续重复的字母是否相同。第一个不同的重复项是您要返回的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句