242. Valid Anagram
- Total Accepted: 135534
- Total Submissions: 300699
- Difficulty: Easy
- Contributors: Admin
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.
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?
Solution 1:用哈希表
1 class Solution { 2 public: 3 //哈希表映射 4 bool isAnagram(string s, string t) { 5 //用map 6 if(s.size() != t.size()) return false; 7 unordered_map<char, int> mp; 8 for(int i = 0; i < s.size(); i++){ 9 mp[s[i]]++; 10 } 11 for(int i = 0; i < t.size(); i++){ 12 mp[t[i]]--; 13 if(mp[t[i]] < 0) return false; 14 } 15 return true; 16 } 17 };
Solution 2:用vector实现hash表
1 class Solution { 2 public: 3 //哈希表映射 4 bool isAnagram(string s, string t) { 5 //用vector 6 if(s.size() != t.size()) return false; 7 vector<int> hash(26, 0); 8 for(int i = 0; i < s.size(); i++){ 9 hash[s[i] - 'a']++; 10 } 11 for(int i = 0; i < t.size(); i++){ 12 hash[t[i] - 'a']--; 13 if(hash[t[i] - 'a'] < 0) return false; 14 } 15 return true; 16 } 17 };