![[LeetCode] Valid Anagram 验证变位词 [LeetCode] Valid Anagram 验证变位词](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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.
这不算一道难题,核心点就在于使用哈希表映射,我们还是用一个数组来代替哈希表,使用类似方法的题目有Minimum Window Substring 最小窗口子串,Isomorphic Strings 同构字符串,Longest Substring Without Repeating Characters 最长无重复子串 和 1.1 Unique Characters of a String 字符串中不同的字符。我们先判断两个字符串长度是否相同,不相同直接返回false。然后把s中所有的字符出现个数统计起来,存入一个大小为26的数组中,因为题目中限定了输入字符串为小写字母组成。然后我们再来统计t字符串,如果发现不匹配则返回false。 参见代码如下:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int m[] = {};
for (int i = ; i < s.size(); ++i) ++m[s[i] - 'a'];
for (int i = ; i < t.size(); ++i) {
if (--m[t[i] - 'a'] < ) return false;
}
return true;
}
};