LeetCode Valid Anagram
题目
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
思路&代码
对于只有小写字母的情况,只需要开一个26个int大小的数组对两个字符串进行字母统计即可,对一个字符串加而对另一个字符串减。这样,如果最后统计数组有一个字符次数不为0,即可知道不一样。
class Solution {
public:
bool isAnagram(string s, string t) {
int charNums[26];
memset(charNums, 0, sizeof(charNums));
for (int i = s.size() - 1; i >= 0; i--) charNums[s[i] - 'a']++;
for (int i = t.size() - 1; i >= 0; i--) {
charNums[t[i] - 'a']--;
if (charNums[t[i] - 'a'] < 0) return false;
}
for (int i = 0; i < 26; i++) if (charNums[i]) return false;
return true;
}
};
但是,如果字符有可能包含Unicode字符,也就是有65536个字符的情况下,当然我们思路也是一样,也可以使用数组来统计。但是这样就会造成极大的空间浪费,所以我选择牺牲时间而节约空间使用map来统计,时间上大概增加了100ms(仅在此题中)。
class Solution {
public:
bool isAnagram(string s, string t) {
map<char, int> hash;
for (int i = s.size() - 1; i >= 0; i--) {
if (hash.find(s[i]) == hash.end()) hash[s[i]] = 1;
else hash[s[i]]++;
}
for (int i = t.size() - 1; i >= 0; i--) {
if (hash.find(t[i]) == hash.end()) return false;
else hash[t[i]]--;
}
for (map<char, int>::iterator iter = hash.begin(); iter != hash.end(); iter++)
if (iter->second != 0) return false;
return true;
}
};