Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Approach 1# Sorting:
class Solution { public: bool isAnagram(string s, string t) { if (s.length() != t.length()) return false; sort(s.begin(), s.end()); sort(t.begin(), t.end()); for (int i = 0; i < s.length(); ++i) { if (s[i] != t[i]) return false; } return true; } };
Runtime: 28 ms
Approach 2# Hash Table:
class Solution { public: bool isAnagram(string s, string t) { if (s.length() != t.length()) return false; vector<int> temp(26, 0); for (int i = 0; i < s.length(); ++i) { temp[s[i]-'a']++; temp[t[i]-'a']--; } for (int i = 0; i < 26; ++i) { if (temp[i] != 0) return false; } return true; } };
Runtime: 8 ms, faster than 83.11% of C++ online submissions for Valid Anagram.