https://leetcode.com/problems/valid-anagram/?tab=Description
思路1:排序
Time complexity: O(nlogn)
Space complexity: O(1)
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
/* 千万不要像下面这么写!!!
if (s == t) return true;
return false;
*/
}
};
思路2:Hash Table
Time complexity: O(n)
Space complexity: O(所有字符种类数量),由于ASCII字符集一共有256种字符编码,所以可以视为常量
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}
vector<int> count(256, 0);
for (char c : s) {
count[(int) c]++;
}
for (char c : t ) {
count[(int) c]--;
if (count[(int) c] < 0) {
return false;
}
}
return true;
}
};