【发布时间】:2015-12-23 01:02:45
【问题描述】:
给定两个字符串 A 和 B,检查它们是否是字谜。
如果一个字符串可以通过重新排列另一个字符串的字母来获得,则称两个字符串为字谜。
字谜的例子是
-
dog, god abac, baac123, 312
abab, aaba 和 dab, baad 不是字谜。
输入:
输入的第一行是测试用例 T 的数量。 后面是T行,每行有两个空格分隔的字符串A和B;
输出
对于每个测试用例,如果它们是字谜,则打印“YES”,否则打印“NO”。 (不带引号)
约束
- 1
- A 和 B 都只包含小写拉丁字母 'a' 到 'z' 和 数字 0 到 9。
- 每个字符串A和B的长度不超过5*10^5 (500000)
`
Sample Input Sample Output
------------------------------------
3 YES
abcd bcda NO
bad daa YES
a1b2c3 abc123 NO
我们怎样才能做到这一点?
bool anagramChecker(string first, string second)
{
if(first.Length != second.Length)
return false;
if(first == second)
return true;//or false: Don't know whether a string counts as an anagram of itself
Dictionary<char, int> pool = new Dictionary<char, int>();
foreach(char element in first.ToCharArray()) //fill the dictionary with that available chars and count them up
{
if(pool.ContainsKey(element))
pool[element]++;
else
pool.Add(element, 1);
}
foreach(char element in second.ToCharArray()) //take them out again
{
if(!pool.ContainsKey(element)) //if a char isn't there at all; we're out
return false;
if(--pool[element] == 0) //if a count is less than zero after decrement; we're out
pool.Remove(element);
}
return pool.Count == 0;
}
【问题讨论】:
-
所以这段代码不起作用??
-
Cheater 方法是对字符进行排序并比较结果序列。
-
老实说,我认为您的解决方案比下面建议的要好。