【发布时间】:2019-11-24 18:13:31
【问题描述】:
给定一个字符数组,我正在寻找找到第一个不同字符及其在数组中的索引的最佳方法。这段代码似乎可以完成这项工作,但我想知道是否有更好的方法可以在没有这么多循环的情况下完成它。感谢您的意见!
static string firstDistinctChar(char[] myChars)
{
string result = "No Distinct Chars found!";
Dictionary<char, int> charDict = new Dictionary<char, int>();
for (int i = 0; i < myChars.Length; i++)
{//create dictionary of char and counts of char in array
if (charDict.TryGetValue(myChars[i], out int count))
{
charDict[myChars[i]] = count + 1;
}
else
{
charDict.Add(myChars[i], 1);
}
}
foreach (var item in charDict)
{
//remove all non distinct chars from dictionary
if (item.Value > 1) { charDict.Remove(item.Key); }
}
for (int i = 0; i < myChars.Length; i++)
{
//loop thru each char in array and return first matching char and index
if (charDict.TryGetValue(myChars[i], out _))
{
result = string.Format("The char: {0} is the first distinct char in the array with an index of : {1}", myChars[i], i);
return result;
}
}
return result;
}
【问题讨论】:
标签: c# arrays dictionary for-loop refactoring