Posted onEdited onInLeetCodeDisqus: Symbols count in article: 838Reading time ≈1 mins.
hashmap O(n) time O(1) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: boolisAnagram(string s, string t){ if (s.length() != t.length()) returnfalse; int f[256] = {0}; for (char c : s) { ++f[c]; } for (char c : t) { if (--f[c] < 0) returnfalse; } returntrue; } };
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: boolisAnagram(string s, string t){ if (size(s) != size(t)) returnfalse; int f[256] = {0}; for (int i = 0; i < size(s); ++i) { ++f[s[i]]; --f[t[i]]; } return all_of(f, f + 256, [](int x){ return x == 0; }); } };
Follow up
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Answer
Use a hash table instead of a fixed size counter. Imagine allocating a large size array to fit the entire range of unicode characters, which could go up to more than 1 million. A hash table is a more generic solution and could adapt to any range of characters.