在下面的代码中,我试图检查两个字符串是否是anagrams。为此,我通过将唯一字符存储为字符串并将其作为值存储在字符串中,计算散列表中两个字符串中的字符。最后,当我检查每个字符是否具有相同的计数时,我会得到一个错误的输出,请参阅代码中标记为“PROBLEM”的行。但是,当我将该行中的值转换为字符串时,代码工作正常。我错过了什么?即使值相同,为什么哈希表中的值比较返回false?
static bool AreAnagrams(string input1, string input2)
{
Hashtable uniqueChars1 = new Hashtable();
Hashtable uniqueChars2 = new Hashtable();
// Go through first string and create a hash table of characters
AddToHashTable(input1, ref uniqueChars1);
// Go through second string and create a second hash table of characters
AddToHashTable(input2, ref uniqueChars2);
// For each unique character, if the count from both hash tables are the same, they are anagrams
if (uniqueChars1.Keys.Count != uniqueChars2.Keys.Count)
{
return false;
}
else
{
foreach (object key in uniqueChars1.Keys)
{
if (uniqueChars1[key] != uniqueChars2[key]) // ***PROBLEM HERE***
{
return false;
}
}
}
return true;
}
static void AddToHashTable(string input, ref Hashtable uniqueChars)
{
foreach (char c in input)
{
if (!uniqueChars.ContainsKey(c))
{
uniqueChars.Add(c, 1);
}
else
{
int charCount = Convert.ToInt32(uniqueChars[c]);
charCount++;
uniqueChars[c] = charCount;
}
}
}
为什么你使用'Hashtable'而不是'Dictionary''? –