Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: 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?
题意:判断异位词,即包含相同的字符的字符串。
方法一:对两个字符串排序,判断排序后的字符串是否相同。
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
方法二:使用map记录每个字符串中的字符,判断map是否相同。
class Solution {
public:
bool isAnagram(string s, string t)
{
return createLog(s) == createLog(t);
}
map<char,int> createLog(string s)
{
map<char,int> log;
for(int i = 0; i < s.size();i++)
{
if(log.find(s[i]) == log.end())
{
log[s[i]] = 0;
}
log[s[i]]++;
}
return log;
}
};