原题描述
Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
分析
如果s和t互为anagram,则他们由相同的字母组成,且对应字母的个数相同。提示使用hashtable,考虑分别将两个字符串的字母和其个数组成键值对存入map。利用map的自动排序功能,同时遍历两个map满足每个键和值都相等则是anagram。
当字符串长度不同时可以快速确定返回false,当字符串都为空串时返回true。
代码示例
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.empty() || t.empty())
return true;
if (s.length() != t.length())
return false;
else
{
map<char, int> records,recordt;
for (string::iterator i = s.begin(), j = t.begin(); i != s.end(); ++i, ++j)
{
if (records.find(*i) == records.end())
records[*i] = 1;
else
records[*i] += 1;
if (recordt.find(*j) == recordt.end())
recordt[*j] = 1;
else
recordt[*j] += 1;
}
for (map<char, int>::iterator i = records.begin(), j = recordt.begin(); i != records.end(); ++i, ++j)
{
if(i->first != j->first || i->second != j->second)
return false;
}
return true;
}
}
};