问题描述
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?
思路分析
给两个string,判断这两个string是否是异位构词,即用相同的字母打乱顺序重新产生一个新词。
因为使用的字母相同,不同字母的个数也相同,可以将两string排序,判断是否相同。
代码
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
时间复杂度:
O(n2)
// Bubble sorting
空间复杂度:
O(1)
反思
可以使用hash table来提升速度。使用unordered_map,建立丛char到int的一个映射,就可以轻松统计每个字符出现的次数了。
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
unordered_map<char, int> count;
for (int i = 0; i < s.length(); i++){
count[s[i]]++;
count[t[i]]--;
}
for (auto i:count){
if (i.second)
return false;
}
return true;
}
};
在开始条件下,如果只有26个小写字母,可以使用数组来模拟一个hash table。
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;
}
};