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.
方法:使用两个map来保持对应的两个字符串的字符个数,对字符个数进行统计,然后遍历两个map看是否完全相同 。
class Solution {
public:
bool isAnagram(string s, string t) {
map<char,int> sMap,tMap;
for(int i=0; i<s.length(); i++)
sMap[s[i]]++;
for(int i=0; i<t.length(); i++)
tMap[t[i]]++;
map<char,int>::iterator sIter,tIter;
sIter=sMap.begin();
tIter=tMap.begin();
while(sIter!=sMap.end() && tIter!=tMap.end() && sIter->first==tIter->first && sIter->second==tIter->second)
{
sIter++;
tIter++;
}
if(sIter==sMap.end() && tIter==tMap.end())
return true;
else
return false;
}
};