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.
翻译:两个字符串s,t,判断t是不是由s中的字符随机排列组成。
2.分析
返回true的要求:s和t中出现的所有字符及其出现次数完全相同。
(1)s,t的长度必须一致
(2)对s,t中的字符计数,判断是否相等。
3.代码
不借助其他数据结构,至少两次遍历
c++
bool isAnagram(string s, string t) {
if (s.size() != t.size())//首先长度要一致。
return false;
int* hashTable = new int[26]();
for (char ch : s)
++hashTable[ch - 'a'];
for (char ch : t) {
--hashTable[ch - 'a'];
if (hashTable[ch - 'a'] < 0)//字符出现次数要一致
return false;
}
return true;
}