242. Valid Anagram
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?
anagram的特质是两个string里所含的字母的frequency一样。计算frequency,想到用hash table。
方法一:用hash table - unordered_map
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.length()!=t.length()){ 5 return false; 6 } 7 unordered_map<char,int> dict; 8 for(char c: s){ 9 dict[c]++; 10 } 11 for(char c:t){ 12 if(dict.find(c)==dict.end()){ 13 return false; 14 }else{ 15 dict[c]--; 16 if(dict[c]==0){ 17 dict.erase(c); 18 } 19 } 20 } 21 22 return dict.size()==0; 23 } 24 };
方法二:此题中涉及的是26个字母,个数是fixed并且有限的,可以考虑自己实现hash table,最简单的就是使用数组:
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.length()!=t.length()){ 5 return false; 6 } 7 vector<int> count(26,0); 8 for(char c: s){ 9 count[c-'a']++; 10 } 11 12 for(char c:t){ 13 if(count[c-'a']==0){ 14 return false; 15 } 16 count[c-'a']--; 17 } 18 19 return true; 20 } 21 };
注意,并不需要loop每个字母查看其个数是否为零。因为我们已经提前判断两个string长度相同,如果第二个string里的某个字母在vector里的count是0,说明不是anagram。
同样,hash table也可以这种判断方法,而不需要将个数为0的字母从hash table里清除。
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 if(s.size()!=t.size()){ 5 return false; 6 } 7 unordered_map<char,int> freq; 8 for(char c:s){ 9 freq[c]++; 10 } 11 for(char c:t){ 12 if(freq[c]==0){ 13 return false; 14 } 15 freq[c]--; 16 } 17 return true; 18 } 19 };