2 C++ Solutions with Explanations
----------\nHash Table\n\nThis idea uses a hash table to record the times of appearances of each letter in the two strings s and t. For each letter in s, it inc
----------\n**Hash Table**\n\nThis idea uses a hash table to record the times of appearances of each letter in the two strings `s` and `t`. For each letter in `s`, it increases the counter by `1` while for each letter in `t`, it decreases the counter by `1`. Finally, all the counters will be `0` if they two are anagrams of each other.\n\nThe first implementation uses the built-in `unordered_map` and takes 36 ms.\n\n    class Solution {\n    public:\n        bool isAnagram(string s, string t) {\n            if (s.length() != t.length()) return false;\n            int n = s.length();\n            unordered_map<char, int> counts;\n            for (int i = 0; i < n; i++) {\n                counts[s[i]]++;\n                counts[t[i]]--;\n            }\n            for (auto count : counts)\n                if (count.second) return false;\n            return true;\n        }\n    };\n\nSince the problem statement says that "the string contains only lowercase alphabets", we can simply use an array to simulate the `unordered_map` and speed up the code. The following implementation takes 12 ms.\n\n    class Solution {\n    public:\n        bool isAnagram(string s, string t) {\n            if (s.length() != t.length()) return false;\n            int n = s.length();\n            int counts[26] = {0};\n            for (int i = 0; i < n; i++) { \n                counts[s[i] - 'a']++;\n                counts[t[i] - 'a']--;\n            }\n            for (int i = 0; i < 26; i++)\n                if (counts[i]) return false;\n            return true;\n        }\n    };\n\n----------\n**Sorting**\n\nFor two anagrams, once they are sorted in a fixed order, they will become the same. This code is much shorter (this idea can be done in just 1 line using Python as [here][1]). However, it takes much longer time --- 76 ms in C++.\n\n    class Solution {\n    public:\n        bool isAnagram(string s, string t) { \n            sort(s.begin(), s.end());\n            sort(t.begin(), t.end());\n            return s == t; \n        }\n    };\n\n  [1]: https://leetcode.com/discuss/49372/python-1-line-solution-88ms
['String', 'C++']