【发布时间】:2015-03-09 02:08:48
【问题描述】:
在下面的代码中,我试图检查两个字符串是否是字谜。为此,我通过将唯一字符存储为键并将其在字符串中的计数存储为值来计算哈希表中两个字符串中的字符。最后,当我去检查每个字符是否具有相同的计数时,我得到一个错误的输出,请参见代码中标记为“问题”的行。但是当我将该行中的值转换为字符串时,代码可以正常工作。我错过了什么?
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;
}
}
}
【问题讨论】: