242. Valid Anagram*
https://leetcode.com/problems/valid-anagram/
题目描述
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?
C++ 实现 0
20210323 更新: 使用哈希表, 注意最后还要保证哈希表为空.
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> record;
for (auto &c : s) record[c] ++;
for (auto &c : t) {
if (!record.count(c)) return false;
record[c] --;
if (record[c] == 0) record.erase(c);
}
return record.empty();
}
};
C++ 实现 1
Anagram 应该是说 t
是由 s
中的字符串任意排列形成的. 要判断 t
是否为 s
的 Anagram, 首先要判断它们大小是否相等, 其次判断 t
中的每种字符的个数是否等于 s
中每种字符的个数.
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map<char, int> A, B;
for (auto &c : s) A[c] ++;
for (auto &c : t) B[c] ++;
for (auto &p : A) {
if (!B.count(p.first) || B[p.first] != p.second) return false;
}
return true;
}
};
C++ 实现 2
由于题目中已经说明 s
和 t
中只包含小写字母, 那么也可以用数组来表示哈希表.
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int record[256] = {0};
for (int i = 0; i < s.size(); ++i) {
record[s[i]] ++;
record[t[i]] --;
}
for (int i = 0; i < 256; ++i)
if (record[i] != 0)
return false;
return true;
}
};