這個問題在這里已經有了答案:
什么想法嗎?
uj5u.com熱心網友回復:
在回圈的每次迭代中,您將 Letter 和 Number 設定為相同的物件參考。嘗試在 foreach 回圈體內實體化新物件:
foreach (char c in word)
{
Occur Oc = new Occur
{
Letter = c,
Number = word.Where(x => x == c).Count()
};
ListNubmersOfWord.Add(Oc);
}
uj5u.com熱心網友回復:
在您的用例中,物件串列不僅效率低下,而且還會在您的示例中導致重復值,您不需要a,b串列中的 char 兩次具有相同的出現次數。我建議使用 a Dictionary<char, int>,你的方法是 O(n) ,其中 n 等于字串中的字符數。您還可以在 O(1) 中查找字符的出現以及在 O(1) 中獲取字符的計數:
string word = "abba";
Dictionary<char, int> charcount = Counter(word);
public static Dictionary<char, int> Counter(string word)
{
Dictionary<char, int> charcount = new Dictionary<char, int>();
foreach (char c in word)
{
if(charcount.ContainsKey(c))
charcount[c] ;
else
charcount.Add(c, 1);
}
return charcount;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466092.html
標籤:C#
下一篇:F#:如何在型別中定義計算屬性?
