标签:
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.
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 using namespace std; 5 6 bool isAnagram(string s, string t) { 7 vector<int> temp1(26,0); 8 vector<int> temp2(26,0); 9 for(auto i=s.begin();i!=s.end();i++) 10 temp1[(*i)-‘a‘]++; 11 for(auto j=t.begin();j!=t.end();j++) 12 temp2[(*j)-‘a‘]++; 13 14 for(int i=0;i<26;i++) 15 if(temp1[i]!=temp2[i]) 16 return false; 17 return true; 18 } 19 20 int main() 21 { 22 string s="anagram"; 23 string t="nagaram"; 24 cout<<isAnagram(s,t)<<endl; 25 system("pause"); 26 }
这道题可以采用哈希表来做:
建立两个哈希表来存储:键为字符,值为个数
然后遍历哈希表,其实这种我做的明显比之前的方法要繁琐,而且非空间,还有要分别遍历两个哈希表。
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 #include<map> 5 using namespace std; 6 7 bool isAnagram(string s, string t) { 8 map<char,int> temp1; 9 map<char,int> temp2; 10 for(auto i=s.begin();i!=s.end();i++) 11 temp1[*i]++; 12 for(auto i=t.begin();i!=t.end();i++) 13 temp2[*i]++; 14 15 for(auto i=temp1.begin();i!=temp1.end();i++) 16 if(i->second!=temp2[i->first]) 17 return false; 18 19 for(auto i=temp2.begin();i!=temp2.end();i++) 20 if(i->second!=temp1[i->first]) 21 return false; 22 23 return true; 24 } 25 26 int main() 27 { 28 string s="anagram"; 29 string t="nagaram"; 30 cout<<isAnagram(s,t)<<endl; 31 system("pause"); 32 }
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4714689.html