我的答案:
class Solution { public: bool isAnagram(string s, string t) { int s1 = 0; int t1 = 0; for (char ss : s) { s1 += ss; } for (char tt : t) { t1 += tt; } if (s1 == t1) { sort(s.begin(), s.end()); sort(t.begin(), t.end()); for (int i = 0; i < s.size(); i++) { if (s[i] != t[i]) { return false; } } return true; } else { return false; } } };
官方使用哈希表解决:
class Solution { public: bool isAnagram(string s, string t) { if (s.length() != t.length()) { return false; } vector<int> table(26, 0); for (auto& ch: s) { table[ch - 'a']++; } for (auto& ch: t) { table[ch - 'a']--; if (table[ch - 'a'] < 0) { return false; } } return true; } };