我正在嘗試回答這個 leetcode 問題:
https://leetcode.com/problems/group-anagrams/
我了解這是哈希圖問題,并且我選擇執行以下操作:
IList<IList<string>> GroupAnagrams(string[] strs)
{
Dictionary<SortedDictionary<char, int>, List<string>> history = new Dictionary<SortedDictionary<char, int>, List<string>>();
foreach (string phrase in strs)
{
SortedDictionary<char, int> signature = new SortedDictionary<char, int>();
foreach (char c in phrase.ToCharArray())
{
if (signature.ContainsKey(c))
{
signature[c] = 1;
}
else
{
signature.Add(c, 1);
}
}
if (history.ContainsKey(signature))
{
history[signature].Add(phrase);
}
else
{
history[signature] = new List<string>();
history[signature].Add(phrase);
}
}
IList<IList<string>> result = new List<IList<string>>();
foreach (var pair in history)
{
result.Add(pair.Value);
}
return list;
}
這個想法是簽名是字符的計數器。如果兩個短語具有相同的簽名,則它們是一個字謎。但是,在通過除錯器單步執行代碼時,我注意到方法呼叫 history.ContainsKey(signature) 永遠不會回傳 true。即使在迭代中監視除錯器中的本地人時也是如此。我想知道這是否是因為簽名應該是一個 SortedDictionary,但這似乎沒有效果。事實上,當我查看當地人的歷史時,它似乎有重復的鍵。誰能解釋發生了什么?
uj5u.com熱心網友回復:
誰能解釋發生了什么?
字典(和排序字典)不是按值比較,而是按參考相等。回傳 true的唯一方法ContainsKey是,作為其引數傳遞的實際物件是否存在于字典中。
換句話說,這段代碼列印了兩次“false”:
Console.WriteLine(new Dictionary<char, int>() == new Dictionary<char, int>());
Console.WriteLine(new Dictionary<char, int> { 'a', 1 } == new Dictionary<char, int> { 'a', 1 });
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457504.html
