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?
AC代码:
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<int,int> map;
unordered_map<int,int>::iterator it;
int len1=s.length();
int len2=t.length();
if(len1!=len2) return false;
for(int i=0;i<len1;i++){
map[s[i]-'a']++;
map[t[i]-'a']--;
}
for(it=map.begin();it!=map.end();it++)
if((it->second)!=0)
return false;
return true;
}
};
这是人家的哈希表,优雅多了。。。哎。。。自己还是很菜啊,不熟悉C++的STL
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
unordered_map<char, int> counts;
for (int i = 0; i < n; i++) {
counts[s[i]]++;
counts[t[i]]--;
}
for (auto count : counts)
if (count.second) return false;
return true;
}
};
事实上用数组就可以办到了:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
int counts[26] = {0};
for (int i = 0; i < n; i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (counts[i]) return false;
return true;
}
};
然后当然最直接的方法是给两个数组排序,然后比较一下一不一样,啊哈哈哈。但是耗时肯定很长了=。=