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.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Subscribe to see which companies asked this question
两种思路。
一种是排序比较是否相等即可。
另一种是利用map做。
map由于是通过树实现的,查找很快,且是遍历string。会比第一种方法快。
代码
被注释掉的就是第一种做法。
class Solution {
public:
bool isAnagram(string s, string t) {
map<char,int> m1;
map<char,int> m2;
for(int i=0;i<s.size();++i)
{
m1[s[i]]++;
}
for(int i=0;i<t.size();++i)
{
m2[t[i]]++;
}
return m1==m2;
// sort(s.begin(),s.end());
// sort(t.begin(),t.end());
// return s==t;
}
};