創建一個存儲類,公開Add(a,b)和類似的函數。內部存儲器可以是HashSet<T>
,其中T是適合的字符串元組鍵。這個Key和comparer唯一重要的是使用對稱的散列和相等函數,即(a,b)等於(b,a),因此散列(a,b)==散列(b,a )。
正如前面指出的,許多散列函數都有這個屬性,例如散列值的和和。我選擇不使用xor,因爲它意味着所有的對等字符串都會有散列零,如果可能的話,可能會導致低效率的查找。
下面的實現假設所有的字符串都是非空的,但沒有錯誤檢查。
public class Storage
{
private HashSet<Key> set;
public Storage()
{
set = new HashSet<Key>(new Key.Comparer());
}
public void Add(string a, string b)
{
set.Add(new Key{A=a, B=b});
}
public bool Contains(string a, string b)
{
return set.Contains(new Key{A=a, B=b});
}
internal class Key
{
internal String A { get; set; }
internal String B { get; set; }
internal class Comparer : IEqualityComparer<Key>
{
public bool Equals(Key x, Key y)
{
return (x.A == y.A && x.B == y.B) || (x.A == y.B && x.B == y.A);
}
public int GetHashCode(Key k)
{
int aHash = k.A.GetHashCode();
int bHash = k.B.GetHashCode();
// Hash for (x,y) same as hash for (y,x)
if (aHash > bHash)
return bHash * 37 + aHash;
return aHash * 37 + bHash;
}
}
}
}
顯然我不能鍵入LT或GT的人物,他們沒有得到逃脫,所以我代替那些括號/圓括號 – pbz 2013-03-24 19:27:25
你有什麼需要用一套呢?例如,您想如何查看價值? – 2013-03-24 19:28:13
@JonSkeet我只需要快速檢查(a1,b1)和(b1,a1)是否已經在集合中。我正在處理大量的這些事情,所以它需要很快。謝謝。 – pbz 2013-03-24 19:29:51