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
看到一个更好的方法:(别人的)
class Solution {public: bool isAnagram(string s, string t) { vector count(26, 0); //全部初始化为0 for(int i = 0; i < s.size(); i ++) count[s[i]-'a'] ++; //把a,b,c转换成下标了- - 不是什么二维,二维应该是vector> for(int i = 0; i < t.size(); i ++) count[t[i]-'a'] --; for(int i = 0; i < 26; i ++) if(count[i] != 0) return false; return true; }};
tips:
string当然不一定要初始化。
C++中没有直接判断map是否相等的函数;
map中有iterator;
map中的元素是pair,我们可以用first来取关键字,second来取值;