标签:
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<map> 2 #include<string> 3 #include<iterator> 4 using namespace std; 5 6 class Solution { 7 public: 8 bool isAnagram(string s, string t) { 9 string temp1,temp2,temp3; 10 int c1,c2; 11 map<string,int> dictionary1,dictionary2; 12 for(int i=0;i<s.length();i++) { 13 temp1=s[i]; 14 ++dictionary1[temp1];} 15 for(int j=0;j<t.length();j++) { 16 temp2=t[j]; 17 ++dictionary2[temp2];} 18 19 if(dictionary1.size()!=dictionary2.size()) return false; 20 for(auto i=dictionary1.begin();i!=dictionary1.end();i++) 21 { 22 c1=(*i).second; 23 temp3=(*i).first; 24 c2=dictionary2[temp3]; 25 if(c1!=c2) return false; 26 } 27 return true; 28 29 } 30 };
tips:
string当然不一定要初始化。
C++中没有直接判断map是否相等的函数;
map中有iterator;
map中的元素是pair,我们可以用first来取关键字,second来取值;
标签:
原文地址:http://www.cnblogs.com/LUO77/p/4959663.html